-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock.js
43 lines (38 loc) · 1.06 KB
/
mock.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
/**
* Mock given function once.
* If `beforeCallback` or `afterCallback` return a truthy value,
* an early return with that value happens.
*
* @param {Function} fun - Function to mock
* @param {Object} config
* @param {Object} config.scope - By default is `window`
* @param {Function} config.beforeCallback
* @param {Function} config.afterCallback
*/
export function mockOnce(fun, { scope = window, beforeCallback = () => { }, afterCallback = () => { } }) {
function restoreScope() {
scope[fun.name] = fun;
}
async function mocked(...args) {
let earlyReturnValue, result, error;
if (earlyReturnValue = await beforeCallback(...args)) {
restoreScope();
return earlyReturnValue;
}
try {
result = await fun(...args);
}
catch (error) {
error = error;
}
finally {
restoreScope();
if (earlyReturnValue = await afterCallback(result, error)) {
return earlyReturnValue;
}
if (error) throw error;
return result;
}
}
scope[fun.name] = (...args) => mocked(...args);
}