UNPKG

eslint-plugin-mocha

Version:

Eslint rules for mocha.

66 lines 2.48 kB
import { createMochaVisitors } from '../ast/mocha-visitors.js'; import { isFunction } from '../ast/node-types.js'; import { findReturnStatement, isReturnOfUndefined } from '../ast/return-statement.js'; 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 !== undefined && node !== null && node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === name; } export const noReturnAndCallbackRule = { 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) { function isAllowedReturnStatement(node, doneName) { if (isReturnOfUndefined(node) || node.argument?.type === 'Literal') { return true; } return isFunctionCallWithName(node.argument, doneName); } function reportIfFunctionWithBlock(node, doneName) { if (node.body.type !== 'BlockStatement') { return; } const returnStatement = findReturnStatement(node.body.body); if (returnStatement !== undefined && !isAllowedReturnStatement(returnStatement, doneName)) { context.report({ node: returnStatement, message: 'Unexpected use of `return` in a test with callback' }); } } function check(node) { if (!isFunction(node)) { return; } const [firstParam] = node.params; if (firstParam?.type !== 'Identifier') { return; } if (!reportIfShortArrowFunction(context, node)) { reportIfFunctionWithBlock(node, firstParam.name); } } return createMochaVisitors(context, { anyTestEntityCallback(visitorContext) { check(visitorContext.node); } }); } }; //# sourceMappingURL=no-return-and-callback.js.map