-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (52 loc) · 1.67 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import util from 'node:util';
function createProxy(impl) {
const calls = [];
const proxy = new Proxy(impl, {
get: function (target, prop, receiver) {
const result = Reflect.get(target, prop, receiver);
if (typeof result === 'function' && typeof prop === 'string') {
const funcProxy = new Proxy(result, {
apply: function (target, thisArg, argumentsList) {
calls.push([prop, argumentsList]);
return target(...argumentsList);
},
});
return funcProxy;
}
return result;
},
});
return { calls, proxy };
}
export function createInterfaceMock(impl) {
const { proxy, calls } = createProxy(impl);
proxy.verify = (cb, { times } = {}) => {
const { proxy: mockProxy, calls: mockCalls } = createProxy(impl);
cb(mockProxy);
if (mockCalls.length > 1) {
throw new Error('Unsupported more than one verify');
}
const mockCall = mockCalls.at(0);
if (!mockCall) {
throw new Error('No calls within verify');
}
const [mockCallName, mockCallArguments] = mockCall;
const originalArguments = calls.filter(c => c[0] === mockCallName).map(c => c[1]);
const equalArguments = originalArguments.filter(a =>
util.isDeepStrictEqual(a, mockCallArguments),
);
if (times !== undefined) {
if (times !== equalArguments.length) {
throw new Error(
`Unmatched calls to .${mockCallName}(), expected calls: ${times}, made calls: ${equalArguments.length}`,
);
}
return;
}
if (equalArguments.length) {
return;
}
throw new Error(`Unmatched calls to .${mockCallName}()`);
};
return proxy;
}