UNPKG

1.57 kBJavaScriptView Raw
1'use strict';
2
3const astUtils = require('../util/ast');
4
5function reportIfShortArrowFunction(context, node) {
6 if (node.body.type !== 'BlockStatement') {
7 context.report({
8 node: node.body,
9 message: 'Confusing implicit return in a test with callback'
10 });
11 return true;
12 }
13 return false;
14}
15
16function isFunctionCallWithName(node, name) {
17 return node.type === 'CallExpression' &&
18 node.callee.type === 'Identifier' &&
19 node.callee.name === name;
20}
21
22function isAllowedReturnStatement(node, doneName) {
23 const argument = node.argument;
24
25 if (astUtils.isReturnOfUndefined(node) || argument.type === 'Literal') {
26 return true;
27 }
28
29 return isFunctionCallWithName(argument, doneName);
30}
31
32function reportIfFunctionWithBlock(context, node, doneName) {
33 const returnStatement = astUtils.findReturnStatement(node.body.body);
34 if (returnStatement && !isAllowedReturnStatement(returnStatement, doneName)) {
35 context.report({
36 node: returnStatement,
37 message: 'Unexpected use of `return` in a test with callback'
38 });
39 }
40}
41
42module.exports = function (context) {
43 function check(node) {
44 if (node.params.length === 0 || !astUtils.hasParentMochaFunctionCall(node)) {
45 return;
46 }
47
48 if (!reportIfShortArrowFunction(context, node)) {
49 reportIfFunctionWithBlock(context, node, node.params[0].name);
50 }
51 }
52
53 return {
54 FunctionExpression: check,
55 ArrowFunctionExpression: check
56 };
57};