forked from avajs/eslint-plugin-ava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathno-async-fn-without-await.js
More file actions
92 lines (81 loc) · 2.2 KB
/
Copy pathno-async-fn-without-await.js
File metadata and controls
92 lines (81 loc) · 2.2 KB
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
import createAvaRule from '../create-ava-rule.js';
import util from '../util.js';
const MESSAGE_ID = 'no-async-fn-without-await';
const MESSAGE_ID_SUGGESTION = 'no-async-fn-without-await-suggestion';
const create = context => {
const ava = createAvaRule(context);
let testUsed = false;
let asyncTest;
let nestedFunctionDepth = 0;
const registerUseOfAwait = () => {
if (asyncTest && nestedFunctionDepth === 0) {
testUsed = true;
}
};
const enterFunction = node => {
if (asyncTest && node !== asyncTest) {
nestedFunctionDepth++;
}
};
const exitFunction = node => {
if (asyncTest && node !== asyncTest) {
nestedFunctionDepth--;
}
};
const isAsync = node => Boolean(node?.async);
return ava.merge({
CallExpression(node) {
if (!ava.isInTestFile() || !ava.isTestNode(node)) {
return;
}
asyncTest = (isAsync(node.arguments[0]) && node.arguments[0])
|| (isAsync(node.arguments[1]) && node.arguments[1]);
},
':function': enterFunction,
':function:exit': exitFunction,
AwaitExpression: registerUseOfAwait,
YieldExpression: registerUseOfAwait,
'ForOfStatement[await=true]': registerUseOfAwait,
'CallExpression:exit'(node) {
if (!ava.isInTestFile() || !ava.isTestNode(node)) {
return;
}
if (asyncTest && !testUsed) {
const {sourceCode} = context;
const asyncToken = sourceCode.getFirstToken(asyncTest, token => token.value === 'async');
context.report({
node: asyncTest,
loc: asyncToken.loc,
messageId: MESSAGE_ID,
suggest: [{
messageId: MESSAGE_ID_SUGGESTION,
fix(fixer) {
const nextToken = sourceCode.getTokenAfter(asyncToken);
return fixer.removeRange([asyncToken.range[0], nextToken.range[0]]);
},
}],
});
}
asyncTest = undefined;
testUsed = false;
nestedFunctionDepth = 0;
},
});
};
export default {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Require async tests to use `await`.',
recommended: true,
url: util.getDocsUrl(import.meta.filename),
},
hasSuggestions: true,
schema: [],
messages: {
[MESSAGE_ID]: 'Function was declared as `async` but doesn\'t use `await`.',
[MESSAGE_ID_SUGGESTION]: 'Remove the `async` keyword.',
},
},
};