ts-mock-imports
Version:
Intuitive mocking for Typescript class imports
69 lines • 2.79 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.InPlaceMockManager = void 0;
var sinonModule = require("sinon");
var sinon = sinonModule;
var InPlaceMockManager = (function () {
function InPlaceMockManager(module, importName) {
this.module = module;
this.importName = importName;
this.classFunctionNames = this.getAllFunctionNames(this.module[this.importName]);
this.original = this.saveOriginal(this.classFunctionNames);
this.mockMethods(this.classFunctionNames);
}
InPlaceMockManager.prototype.mock = function (funcName, returns) {
return this.mockFunction(funcName, returns);
};
InPlaceMockManager.prototype.getMockInstance = function () {
return new this.module[this.importName]();
};
InPlaceMockManager.prototype.restore = function () {
var _this = this;
this.classFunctionNames.forEach(function (funcName) {
if (_this.original[funcName]) {
_this.module[_this.importName].prototype[funcName] = _this.original[funcName];
}
});
};
InPlaceMockManager.prototype.mockFunction = function (funcName, returns) {
var spy = sinon.stub();
spy.returns(returns);
this.replaceFunction(funcName, spy);
return spy;
};
InPlaceMockManager.prototype.replaceFunction = function (funcName, newFunc) {
this.replace(funcName, newFunc);
};
InPlaceMockManager.prototype.replace = function (name, arg) {
this.module[this.importName].prototype[name] = arg;
};
InPlaceMockManager.prototype.getAllFunctionNames = function (obj) {
var funcNames = [];
do {
funcNames = funcNames.concat(Object.getOwnPropertyNames(obj.prototype)
.filter(function (property) { return typeof obj.prototype[property] === 'function'; }));
obj = Object.getPrototypeOf(obj);
} while (obj && obj.prototype && obj.prototype !== Object.prototype);
return funcNames;
};
InPlaceMockManager.prototype.saveOriginal = function (functionNames) {
var _this = this;
var original = {};
functionNames.forEach(function (funcName) {
original[funcName] = _this.module[_this.importName].prototype[funcName];
});
return original;
};
InPlaceMockManager.prototype.mockMethods = function (functionNames) {
var _this = this;
functionNames.forEach(function (funcName) {
if (funcName === 'constructor') {
return;
}
_this.mock(funcName);
});
};
return InPlaceMockManager;
}());
exports.InPlaceMockManager = InPlaceMockManager;
//# sourceMappingURL=in-place-manager.js.map