eslint-plugin-mocha
Version:
Eslint rules for mocha.
109 lines • 3.84 kB
JavaScript
import { createMochaVisitors } from "../ast/mocha-visitors.js";
import { expectNodeRange } from "../ast/node-location.js";
function isNamedExportWithDeclaration(node) {
return node.type === 'ExportNamedDeclaration' && node.declaration !== null;
}
function isNamedDefaultExportDeclaration(node) {
return node.type === 'ExportDefaultDeclaration' &&
(node.declaration.type === 'ClassDeclaration' || node.declaration.type === 'FunctionDeclaration') &&
node.declaration.id !== null;
}
function isLocalNamedExportList(node) {
return node.type === 'ExportNamedDeclaration' &&
node.source === null;
}
function fixRemoveExportKeyword(fixer, node, declaration) {
const range = expectNodeRange(node);
const declarationRange = expectNodeRange(declaration);
return fixer.removeRange([range[0], declarationRange[0]]);
}
function fixRemoveDefaultExportKeyword(fixer, node) {
return fixRemoveExportKeyword(fixer, node, node.declaration);
}
function fixRemoveExportStatement(fixer, node) {
return fixer.removeRange(expectNodeRange(node));
}
function createExportSuggestions(node) {
if (isNamedExportWithDeclaration(node)) {
return [{
messageId: 'removeExportKeyword',
fix(fixer) {
return fixRemoveExportKeyword(fixer, node, node.declaration);
}
}];
}
if (isNamedDefaultExportDeclaration(node)) {
return [{
messageId: 'removeExportKeyword',
fix(fixer) {
return fixRemoveDefaultExportKeyword(fixer, node);
}
}];
}
if (isLocalNamedExportList(node)) {
return [{
messageId: 'removeExportStatement',
fix(fixer) {
return fixRemoveExportStatement(fixer, node);
}
}];
}
return [];
}
export const noExportsRule = {
meta: {
type: 'suggestion',
docs: {
description: 'Disallow exports from test files',
recommended: true,
url: 'https://github.com/lo1tuma/eslint-plugin-mocha/blob/main/documentation/rules/no-exports.md'
},
hasSuggestions: true,
schema: [],
messages: {
unexpectedExport: 'Unexpected export from a test file',
removeExportKeyword: 'Remove the export keyword',
removeExportStatement: 'Remove this export statement'
},
languages: ['js/js']
},
create(context) {
const exportNodes = [];
let hasTestCase = false;
return createMochaVisitors(context, {
'Program:exit'() {
if (!hasTestCase || exportNodes.length === 0) {
return;
}
for (const node of exportNodes) {
const suggestions = createExportSuggestions(node);
context.report(suggestions.length === 0
? {
node,
messageId: 'unexpectedExport'
}
: {
node,
messageId: 'unexpectedExport',
suggest: suggestions
});
}
},
anyTestEntity() {
if (!hasTestCase) {
hasTestCase = true;
}
},
ExportNamedDeclaration(node) {
exportNodes.push(node);
},
ExportDefaultDeclaration(node) {
exportNodes.push(node);
},
ExportAllDeclaration(node) {
exportNodes.push(node);
}
});
}
};
//# sourceMappingURL=no-exports.js.map