-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsrc.js
74 lines (60 loc) · 2.09 KB
/
src.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
69
70
71
72
73
74
export const mock_api = return_arg => {
const _calls = [];
const proxy = new Proxy(function () {}, {
apply(target, this_arg, _args) {
// function called initially
const call = { _args }
_calls.push(call);
return make_sub_proxy(call);
},
get(target, key) {
// get _calls
if (key == '_calls') return _calls;
// await foo().bar() will resolve to return_arg
else if (key == 'then') return resolve => resolve(return_arg);
// property accessed initially
else {
const call = { [key]: {} };
_calls.push(call);
return make_sub_proxy(call);
}
}
});
const make_sub_proxy = call => {
// traverse to the current position in call_list
let temp = call;
for (let key in temp) {
if (key != '_args') temp = temp[key];
}
const sub_proxy = new Proxy(function () {}, {
apply(target, this_arg, _args) {
// function called
// foo('a','b','c')
if (!temp.hasOwnProperty('_args')) temp._args = _args;
// function called without explicit name
// foo('a','b','c')(1,2,3)
else {
temp._anonymous = { _args };
temp = temp._anonymous;
}
return sub_proxy;
},
get(target, key) {
// get _calls
if (key == '_calls') return _calls;
// await foo().bar() will resolve to return_arg
else if (key == 'then') return resolve => resolve(return_arg);
// property accessed
else {
temp[key] = {};
temp = temp[key];
return sub_proxy;
}
}
});
return sub_proxy;
};
return proxy;
};
// call_fn: api => api.foo().bar()
export const mock_call = call_fn => call_fn(mock_api())._calls[0];