/
no-async-describe.js
82 lines (72 loc) · 2.75 KB
/
no-async-describe.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
'use strict';
/* eslint "complexity": [ "error", 5 ] */
/**
* @fileoverview Disallow async functions as arguments to describe
*/
const createAstUtils = require('../util/ast');
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Disallow async functions passed to describe',
url: 'https://github.com/lo1tuma/eslint-plugin-mocha/blob/main/docs/rules/no-async-describe.md'
},
fixable: 'code',
schema: []
},
create(context) {
const astUtils = createAstUtils(context.settings);
const sourceCode = context.getSourceCode();
function isFunction(node) {
return (
node.type === 'FunctionExpression' ||
node.type === 'FunctionDeclaration' ||
node.type === 'ArrowFunctionExpression'
);
}
function containsDirectAwait(node) {
if (node.type === 'AwaitExpression') {
return true;
} else if (node.type && !isFunction(node)) {
return Object.keys(node).some(function (key) {
if (Array.isArray(node[key])) {
return node[key].some(containsDirectAwait);
} else if (key !== 'parent' && node[key] && typeof node[key] === 'object') {
return containsDirectAwait(node[key]);
}
return false;
});
}
return false;
}
function fixAsyncFunction(fixer, fn) {
if (!containsDirectAwait(fn.body)) {
// Remove the "async" token and all the whitespace before "function":
const [ asyncToken, functionToken ] = sourceCode.getFirstTokens(fn, 2);
return fixer.removeRange([ asyncToken.range[0], functionToken.range[0] ]);
}
return undefined;
}
function isAsyncFunction(node) {
return node && (node.type === 'FunctionExpression' ||
node.type === 'ArrowFunctionExpression') && node.async;
}
return {
CallExpression(node) {
const name = astUtils.getNodeName(node.callee);
if (astUtils.isDescribe(node)) {
const fnArg = node.arguments.slice(-1)[0];
if (isAsyncFunction(fnArg)) {
context.report({
node: fnArg,
message: `Unexpected async function in ${name}()`,
fix(fixer) {
return fixAsyncFunction(fixer, fnArg);
}
});
}
}
}
};
}
};