inceptum
Version:
hipages take on the foundational library for enterprise-grade apps written in NodeJS
113 lines • 3.44 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class MockObj {
constructor(objProto) {
this.objProto = objProto;
}
}
exports.MockObj = MockObj;
class MyProxyHandler {
constructor(baseClass) {
this.baseClass = baseClass;
this.expects = [];
}
get(target, p, receiver) {
// console.log('Call to get with: ', target, p);
if (p === '__getTarget') {
return target;
}
if (p === '__getProxyHandler') {
return this;
}
if (this.baseClass.prototype[p] && this.baseClass.prototype[p] instanceof Function) {
const func = (...args) => {
return this.doCall(target, p, args);
};
func['__name'] = p;
func['__handler'] = this;
return func;
}
return target[p];
}
registerExpect(funcName, args, resp) {
// console.log('Registering: ', funcName, args, resp);
this.expects.push({ funcName, args, resp });
}
doCall(target, p, args) {
// console.log('Doing actual call with', target, p, args);
const realArgs = (args === undefined) ? [] : args;
const expect = this.expects.find((e) => {
return (e.funcName === p) && arrEqual(e.args, args);
});
if (expect) {
// console.log('Got expect', expect);
return expect.resp;
}
throw new Error(`Unexpected mock call of method ${p} with args: ${args}`);
}
}
exports.MyProxyHandler = MyProxyHandler;
function mock(clazz, target) {
const o = {};
return new Proxy(target ? target : o, new MyProxyHandler(clazz));
}
exports.mock = mock;
class ResponseCapture {
constructor(handler, functionName, args) {
this.handler = handler;
this.functionName = functionName;
this.args = args;
}
thenReturn(resp) {
this.handler.registerExpect(this.functionName, this.args, resp);
}
}
exports.ResponseCapture = ResponseCapture;
class CallCapture {
constructor(handler, functionName) {
this.handler = handler;
this.functionName = functionName;
}
isCalled() {
this.args = [];
return new ResponseCapture(this.handler, this.functionName, []);
}
isCalledWith(...args) {
this.args = args;
return new ResponseCapture(this.handler, this.functionName, args);
}
}
exports.CallCapture = CallCapture;
function when(f) {
if (f && f['__handler']) {
return new CallCapture(f['__handler'], f['__name']);
}
throw new Error('Can only when on mock objects');
}
exports.when = when;
function arrEqual(arr1, arr2) {
if (arr1 === arr2) {
return true;
}
if (arr1.length !== arr2.length) {
return false;
}
if ((arr1 === undefined) || (arr2 === undefined)) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
// Check if we have nested arrays
if (arr1[i] instanceof Array && arr2[i] instanceof Array) {
// recurse into the nested arrays
if (!arrEqual(arr1[i], arr2[i])) {
return false;
}
}
else if (arr1[i] !== arr2[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
//# sourceMappingURL=TestUtil.js.map