Syntax previewClick to edit
1234
export default function myNew(Constructor, ...args) {
throw new Error('Not implemented');
}
Syntax previewClick to edit
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
import myNew from './file';
describe('myNew', () => {
test('creates an instance with correct prototype and runs constructor', () => {
function Person(name) { this.name = name; }
Person.prototype.say = function() { return `hi ${this.name}`; };
const p = myNew(Person, 'Ada');
expect(p.name).toBe('Ada');
expect(p.say()).toBe('hi Ada');
expect(p instanceof Person).toBe(true);
});
test('returns object returned by constructor (override rule)', () => {
function Factory(name) {
this.name = name;
return { ok: true, name };
}
const f = myNew(Factory, 'Ada');
expect(f).toEqual({ ok: true, name: 'Ada' });
});
test('ignores primitive returned by constructor', () => {
function Weird(name) {
this.name = name;
return 123;
}
const w = myNew(Weird, 'Ada');
expect(w.name).toBe('Ada');
expect(w instanceof Weird).toBe(true);
});
test('treats null return as no override', () => {
function NullReturn(name) {
this.name = name;
return null;
}
const n = myNew(NullReturn, 'Ada');
expect(n.name).toBe('Ada');
expect(n instanceof NullReturn).toBe(true);
});
});
Run tests to see results.