UNPKG

eslint-plugin-mocha

Version:

Eslint rules for mocha.

86 lines 3.03 kB
import { createMochaVisitors } from "../ast/mocha-visitors.js"; import { isBlockStatement } from "../ast/node-types.js"; import { getRuleOption } from "../rule-options.js"; const asyncMethods = ['async', 'callback', 'promise']; const optionSchema = { type: 'object', properties: { allowedAsyncMethods: { type: 'array', items: { type: 'string', enum: asyncMethods }, minItems: 1, uniqueItems: true } }, additionalProperties: false }; const defaultOption = { allowedAsyncMethods: Array.from(asyncMethods) }; function hasAsyncCallback(functionExpression) { return functionExpression.params.length === 1; } function isAsyncFunction(functionExpression) { return functionExpression.async === true; } function findPromiseReturnStatement(nodes) { return nodes.find(function (node) { return (node.type === 'ReturnStatement' && node.argument !== null && node.argument?.type !== 'Literal'); }); } function doesReturnPromise(functionExpression) { const bodyStatement = functionExpression.body; let returnStatement = null; if (isBlockStatement(bodyStatement)) { returnStatement = findPromiseReturnStatement(bodyStatement.body); } else if (bodyStatement.type !== 'Literal') { // allow arrow statements calling a promise with implicit return. returnStatement = bodyStatement; } return returnStatement !== null && returnStatement !== undefined; } const asyncChecksByMethod = { async: isAsyncFunction, callback: hasAsyncCallback, promise: doesReturnPromise }; export const noSynchronousTestsRule = { meta: { type: 'suggestion', docs: { description: 'Disallow synchronous tests', recommended: false, url: 'https://github.com/lo1tuma/eslint-plugin-mocha/blob/main/documentation/rules/no-synchronous-tests.md' }, schema: [optionSchema], defaultOptions: [defaultOption], messages: { unexpectedSynchronousTest: 'Unexpected synchronous test.' }, languages: ['js/js'] }, create(context) { const { allowedAsyncMethods } = getRuleOption(context); const asyncChecks = allowedAsyncMethods.map(function (method) { return asyncChecksByMethod[method]; }); return createMochaVisitors(context, { anyTestEntityCallback(visitorContext) { if (visitorContext.type !== 'testCase' && visitorContext.type !== 'hook') { return; } for (const checkAsync of asyncChecks) { if (checkAsync(visitorContext.node)) { return; } } context.report({ node: visitorContext.node, messageId: 'unexpectedSynchronousTest' }); } }); } }; //# sourceMappingURL=no-synchronous-tests.js.map