-
Notifications
You must be signed in to change notification settings - Fork 227
/
no-test-callback.ts
100 lines (83 loc) · 2.88 KB
/
no-test-callback.ts
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
100
import { createRule, isFunction, isTestCase } from './tsUtils';
export default createRule({
name: __filename,
meta: {
docs: {
category: 'Best Practices',
description: 'Avoid using a callback in asynchronous tests',
recommended: false,
},
messages: {
illegalTestCallback: 'Illegal usage of test callback',
},
fixable: 'code',
schema: [],
type: 'suggestion',
},
defaultOptions: [],
create(context) {
return {
CallExpression(node) {
if (!isTestCase(node) || node.arguments.length !== 2) {
return;
}
const [, callback] = node.arguments;
if (!isFunction(callback) || callback.params.length !== 1) {
return;
}
const [argument] = callback.params;
context.report({
node: argument,
messageId: 'illegalTestCallback',
fix(fixer) {
const { body } = callback;
if (!body) {
throw new Error('Unexpected null - please file a github issue');
}
const sourceCode = context.getSourceCode();
const firstBodyToken = sourceCode.getFirstToken(body);
const lastBodyToken = sourceCode.getLastToken(body);
const tokenBeforeArgument = sourceCode.getTokenBefore(argument);
const tokenAfterArgument = sourceCode.getTokenAfter(argument);
if (
!('name' in argument) ||
!firstBodyToken ||
!lastBodyToken ||
!tokenBeforeArgument ||
!tokenAfterArgument
) {
throw new Error('Unexpected null - please file a github issue');
}
const argumentInParens =
tokenBeforeArgument.value === '(' &&
tokenAfterArgument.value === ')';
let argumentFix = fixer.replaceText(argument, '()');
if (argumentInParens) {
argumentFix = fixer.remove(argument);
}
let newCallback = argument.name;
if (argumentInParens) {
newCallback = `(${newCallback})`;
}
let beforeReplacement = `new Promise(${newCallback} => `;
let afterReplacement = ')';
let replaceBefore = true;
if (body.type === 'BlockStatement') {
const keyword = callback.async ? 'await' : 'return';
beforeReplacement = `${keyword} ${beforeReplacement}{`;
afterReplacement += '}';
replaceBefore = false;
}
return [
argumentFix,
replaceBefore
? fixer.insertTextBefore(firstBodyToken, beforeReplacement)
: fixer.insertTextAfter(firstBodyToken, beforeReplacement),
fixer.insertTextAfter(lastBodyToken, afterReplacement),
];
},
});
},
};
},
});