forked from nodejs/node-api-cts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmust-call.js
More file actions
46 lines (42 loc) · 1.07 KB
/
must-call.js
File metadata and controls
46 lines (42 loc) · 1.07 KB
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
const pendingCalls = [];
/**
* Wraps a function and asserts it is called exactly `exact` times before the
* process exits. If `fn` is omitted, a no-op function is used.
*
* Usage:
* promise.then(mustCall((result) => {
* assert.strictEqual(result, 42);
* }));
*/
const mustCall = (fn, exact = 1) => {
const entry = {
exact,
actual: 0,
name: fn?.name || "<anonymous>",
error: new Error(), // capture call-site stack
};
pendingCalls.push(entry);
return function(...args) {
entry.actual++;
if (fn) return fn.apply(this, args);
};
};
/**
* Returns a function that throws immediately if called.
*/
const mustNotCall = (msg) => {
return () => {
throw new Error(msg || "mustNotCall function was called");
};
};
process.on("exit", () => {
for (const entry of pendingCalls) {
if (entry.actual !== entry.exact) {
entry.error.message =
`mustCall "${entry.name}" expected ${entry.exact} call(s) ` +
`but got ${entry.actual}`;
throw entry.error;
}
}
});
Object.assign(globalThis, { mustCall, mustNotCall });