Syntax previewClick to edit
1234
export default function myNew(Constructor, ...args) {
throw new Error('Not implemented');
}
Syntax previewClick to edit
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
import myNew from './file';
describe('myNew', () => {
test('constructs classic functions with their prototype', () => {
function Person(name) { this.name = name; }
Person.prototype.say = function() { return 'hi ' + this.name; };
const person = myNew(Person, 'Ada');
expect(person.name).toBe('Ada');
expect(person.say()).toBe('hi Ada');
expect(person instanceof Person).toBe(true);
});
test('constructs ES classes', () => {
class Account {
constructor(id) { this.id = id; }
}
const account = myNew(Account, 42);
expect(account.id).toBe(42);
expect(account instanceof Account).toBe(true);
});
test('constructs bound targets with native prototype behavior', () => {
function Person(prefix, name) { this.label = prefix + ' ' + name; }
const BoundPerson = Person.bind(null, 'Dr.');
const person = myNew(BoundPerson, 'Ada');
expect(person.label).toBe('Dr. Ada');
expect(person instanceof Person).toBe(true);
expect(person instanceof BoundPerson).toBe(true);
});
test('provides the constructor as new.target', () => {
function CaptureTarget() { this.seen = new.target; }
expect(myNew(CaptureTarget).seen).toBe(CaptureTarget);
});
test('falls back to Object.prototype for non-object prototypes', () => {
function NullPrototype() {}
NullPrototype.prototype = null;
function PrimitivePrototype() {}
PrimitivePrototype.prototype = 7;
expect(Object.getPrototypeOf(myNew(NullPrototype))).toBe(Object.prototype);
expect(Object.getPrototypeOf(myNew(PrimitivePrototype))).toBe(Object.prototype);
});
test('honors object and function return overrides', () => {
function ReturnsObject() { return { ok: true }; }
function ReturnsFunction() { return function returned() {}; }
expect(myNew(ReturnsObject)).toEqual({ ok: true });
expect(typeof myNew(ReturnsFunction)).toBe('function');
});
test('ignores primitive and null returns', () => {
function ReturnsPrimitive() { this.ok = true; return 123; }
function ReturnsNull() { this.ok = true; return null; }
expect(myNew(ReturnsPrimitive).ok).toBe(true);
expect(myNew(ReturnsNull).ok).toBe(true);
});
test('throws TypeError for callable but nonconstructable targets', () => {
const arrow = () => {};
const method = ({ run() {} }).run;
expect(() => myNew(arrow)).toThrow(TypeError);
expect(() => myNew(method)).toThrow(TypeError);
});
});
Run tests to see results.