UNPKG

eslint-plugin-mocha

Version:

Eslint rules for mocha.

59 lines 2.22 kB
import { createMochaVisitors } from "../ast/mocha-visitors.js"; import { findReturnStatement } from "../ast/return-statement.js"; import { getIdentifierCallbackParameter } from "../mocha/callback-parameter.js"; import { isLiteralOrUndefinedReturn } from "./mocha-return-rule.js"; function isFunctionCallWithName(node, name) { return node?.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === name; } function isAllowedReturnStatement(node, callbackName) { if (isLiteralOrUndefinedReturn(node)) { return true; } return isFunctionCallWithName(node.argument, callbackName); } function checkNodeForReturnAndDone(context, node) { const callbackParameter = getIdentifierCallbackParameter(node); if (callbackParameter === undefined) { return; } if (node.body.type !== 'BlockStatement') { context.report({ node: node.body, messageId: 'implicitReturnWithCallback' }); return; } const returnStatement = findReturnStatement(node.body.body); if (returnStatement !== undefined && !isAllowedReturnStatement(returnStatement, callbackParameter.name)) { context.report({ node: returnStatement, messageId: 'unexpectedReturnWithCallback' }); } } export const noReturnAndDoneRule = { meta: { type: 'problem', docs: { description: 'Disallow returning in a test or hook function that uses a callback', recommended: true, url: 'https://github.com/lo1tuma/eslint-plugin-mocha/blob/main/documentation/rules/no-return-and-done.md' }, schema: [], messages: { implicitReturnWithCallback: 'Confusing implicit return in a test with callback', unexpectedReturnWithCallback: 'Unexpected use of `return` in a test with callback' }, languages: ['js/js'] }, create(context) { return createMochaVisitors(context, { anyTestEntityCallback(visitorContext) { checkNodeForReturnAndDone(context, visitorContext.node); } }); } }; //# sourceMappingURL=no-return-and-done.js.map