/
no-return-and-callback.js
69 lines (58 loc) · 2.05 KB
/
no-return-and-callback.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
'use strict';
const createAstUtils = require('../util/ast');
function reportIfShortArrowFunction(context, node) {
if (node.body.type !== 'BlockStatement') {
context.report({
node: node.body,
message: 'Confusing implicit return in a test with callback'
});
return true;
}
return false;
}
function isFunctionCallWithName(node, name) {
return node.type === 'CallExpression' &&
node.callee.type === 'Identifier' &&
node.callee.name === name;
}
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Disallow returning in a test or hook function that uses a callback',
url: 'https://github.com/lo1tuma/eslint-plugin-mocha/blob/main/docs/rules/no-return-and-callback.md'
},
schema: []
},
create(context) {
const astUtils = createAstUtils(context.settings);
function isAllowedReturnStatement(node, doneName) {
const argument = node.argument;
if (astUtils.isReturnOfUndefined(node) || argument.type === 'Literal') {
return true;
}
return isFunctionCallWithName(argument, doneName);
}
function reportIfFunctionWithBlock(node, doneName) {
const returnStatement = astUtils.findReturnStatement(node.body.body);
if (returnStatement && !isAllowedReturnStatement(returnStatement, doneName)) {
context.report({
node: returnStatement,
message: 'Unexpected use of `return` in a test with callback'
});
}
}
function check(node) {
if (node.params.length === 0 || !astUtils.hasParentMochaFunctionCall(node)) {
return;
}
if (!reportIfShortArrowFunction(context, node)) {
reportIfFunctionWithBlock(node, node.params[0].name);
}
}
return {
FunctionExpression: check,
ArrowFunctionExpression: check
};
}
};