-
Notifications
You must be signed in to change notification settings - Fork 109
/
jest-rm-mock.js
74 lines (68 loc) · 2.08 KB
/
jest-rm-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
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
const path = require('path');
module.exports = function(file, api, options = {}) {
if (
!file.path.includes(path.sep + '__tests__' + path.sep) &&
!file.path.includes(path.sep + '__mocks__' + path.sep)
) {
return null;
}
const j = api.jscodeshift;
const printOptions = options.printOptions || {quote: 'single'};
const root = j(file.source);
const JEST = 'jest';
const isJestFn = node => (
['mock', 'unmock', 'disableAutomock'].includes(node.name)
);
const removeCalls = (moduleNames) => {
let mutated = false;
const isJest = node => (
node.type == 'CallExpression' &&
node.callee.type == 'MemberExpression' &&
isJestFn(node.callee.property)
);
const shouldUpdate = node => (
node.type == 'CallExpression' &&
node.callee.type == 'MemberExpression' &&
node.callee.property.name == 'mock' &&
node.arguments.some(arg => moduleNames.includes(arg.value))
);
const descend = (parent, node) => {
if (node && isJest(node)) {
if (shouldUpdate(node)) {
mutated = true;
parent.callee.object = node.callee.object;
node = parent;
}
descend(node, node.callee.object);
}
};
const update = statement => {
const expression = statement.expression;
if (isJest(expression)) {
descend(expression, expression.callee.object);
}
if (shouldUpdate(expression)) {
mutated = true;
statement.expression = expression.callee.object;
update(statement);
return true;
}
};
const program = root.get(0).node.program;
const body = program.body.filter((statement, index) => {
if (statement.type === 'ExpressionStatement' && update(statement)) {
if (
statement.expression.type == 'Identifier' &&
statement.expression.name == JEST
) {
return false;
}
}
return true;
});
program.body = body;
return mutated;
};
const mutations = removeCalls(options.moduleNames);
return mutations ? root.toSource(printOptions) : null;
};