@microphi/di
Version:
Handcrafted DI container
52 lines (51 loc) • 1.67 kB
JavaScript
const MockedSymbol = Symbol('Mocked');
export const Mocked = (base, options = {}) => {
var _a, _b;
return _b = class {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
constructor(...ops) {
this[_a] = true;
const methods = [...getPropertyNames(base.prototype)];
methods
.forEach((m) => {
if (m in options) {
if (options[m] === 'NO_MOCK') {
this[m] = base.prototype[m];
}
if (options[m] !== 'NO_MOCK' && typeof options[m] === 'function') {
this[m] = options[m];
}
}
else {
this[m] = jest.fn();
}
});
}
},
_a = MockedSymbol,
_b;
};
function* getPropertyNames(instance) {
const internals = ['constructor', '__defineGetter__',
'__defineSetter__',
'hasOwnProperty',
'__lookupGetter__',
'__lookupSetter__',
'isPrototypeOf',
'propertyIsEnumerable',
'toString',
'valueOf',
'toLocaleString'
];
while (instance) {
const methods = Object.getOwnPropertyNames(instance)
.filter((property) => {
return typeof instance[property] === 'function';
})
.filter((p) => !internals.includes(p));
for (const method of methods) {
yield method;
}
instance = Object.getPrototypeOf(instance);
}
}