-
Notifications
You must be signed in to change notification settings - Fork 6
/
extract-calls-fake.js
99 lines (96 loc) · 2.47 KB
/
extract-calls-fake.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
function transformer(file, api) {
const j = api.jscodeshift;
const source = j(file.source);
const replacer = path => {
let callNode = path.node;
// console.log('EXP', path.node);
let fakeImplementationNode = callNode.arguments.pop();
// sinon.stub(obj, 'foo', function () { return 'boom'; })
// sinon.stub(obj, 'foo', () => {})
// sinon.stub(obj, 'foo', someFunc)
if (
[
'FunctionExpression',
'ArrowFunctionExpression',
'Identifier',
'CallExpression'
].includes(fakeImplementationNode.type)
) {
return j.memberExpression(
callNode,
j.callExpression(j.identifier('callsFake'), [fakeImplementationNode])
);
} else if (fakeImplementationNode.type === 'ObjectExpression') {
// getter/setter
const properties = fakeImplementationNode.properties;
if (!properties) {
return;
}
// { get: fake, set: fake } pattern is not supported yet.
if (properties.length > 1) {
throw new Error('NOT support');
}
const property = properties[0];
if (property.kind !== 'init' || !property.key) {
return;
}
if (property.key.name !== 'get' && property.key.name !== 'set') {
return; // this is not getter or setter
}
const isGetter = property.key.name === 'get';
// => stub(obj, "prop").get(fn)
if (isGetter) {
return j.memberExpression(
callNode,
j.callExpression(j.identifier('get'), [property.value])
);
} else {
// => stub(obj, "prop").set(fn)
return j.memberExpression(
callNode,
j.callExpression(j.identifier('set'), [property.value])
);
}
}
};
source
.find(j.CallExpression, {
callee: {
object: {
name: 'sinon'
},
property: {
name: 'stub'
}
},
arguments: {
length: 3
}
})
.replaceWith(replacer);
return source
.find(j.CallExpression, {
callee: {
type: 'MemberExpression',
object: {
type: 'MemberExpression',
object: {
type: 'ThisExpression'
},
property: {
type: 'Identifier',
name: '_sandbox'
}
},
property: {
name: 'stub'
}
},
arguments: {
length: 3
}
})
.replaceWith(replacer)
.toSource();
}
module.exports = transformer;