-
Notifications
You must be signed in to change notification settings - Fork 63
/
no-synchronous-tests.js
105 lines (90 loc) · 3.14 KB
/
no-synchronous-tests.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
100
101
102
103
104
105
'use strict';
const { isNil, find } = require('rambda');
const createAstUtils = require('../util/ast');
const asyncMethods = [ 'async', 'callback', 'promise' ];
function hasAsyncCallback(functionExpression) {
return functionExpression.params.length === 1;
}
function isAsyncFunction(functionExpression) {
return functionExpression.async === true;
}
function findPromiseReturnStatement(nodes) {
return find(function (node) {
return (
node.type === 'ReturnStatement' &&
node.argument &&
node.argument.type !== 'Literal'
);
}, nodes);
}
function doesReturnPromise(functionExpression) {
const bodyStatement = functionExpression.body;
let returnStatement = null;
if (bodyStatement.type === 'BlockStatement') {
returnStatement = findPromiseReturnStatement(
functionExpression.body.body
);
} else if (bodyStatement.type !== 'Literal') {
// allow arrow statements calling a promise with implicit return.
returnStatement = bodyStatement;
}
return returnStatement !== null && typeof returnStatement !== 'undefined';
}
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'Disallow synchronous tests',
url: 'https://github.com/lo1tuma/eslint-plugin-mocha/blob/main/docs/rules/no-synchronous-tests.md'
},
schema: [
{
type: 'object',
properties: {
allowed: {
type: 'array',
items: {
type: 'string',
enum: asyncMethods
},
minItems: 1,
uniqueItems: true
}
}
}
]
},
create(context) {
const astUtils = createAstUtils(context.settings);
const options = context.options[0] || {};
const allowedAsyncMethods = isNil(options.allowed) ?
asyncMethods :
options.allowed;
function check(node) {
if (astUtils.hasParentMochaFunctionCall(node)) {
// For each allowed async test method, check if it is used in the test
const testAsyncMethods = allowedAsyncMethods.map(function (
method
) {
switch (method) {
case 'async':
return isAsyncFunction(node);
case 'callback':
return hasAsyncCallback(node);
default:
return doesReturnPromise(node);
}
});
// Check that at least one allowed async test method is used in the test
const isAsyncTest = testAsyncMethods.includes(true);
if (!isAsyncTest) {
context.report({ node, message: 'Unexpected synchronous test.' });
}
}
}
return {
FunctionExpression: check,
ArrowFunctionExpression: check
};
}
};