|
| 1 | +import { |
| 2 | + AST_NODE_TYPES, |
| 3 | + TSESTree, |
| 4 | +} from '@typescript-eslint/experimental-utils'; |
| 5 | +import { createRule, isTestCase } from './tsUtils'; |
| 6 | + |
| 7 | +export default createRule({ |
| 8 | + name: __filename, |
| 9 | + meta: { |
| 10 | + docs: { |
| 11 | + category: 'Best Practices', |
| 12 | + description: |
| 13 | + 'Prevents exports from test files. If a file has at least 1 test in it, then this rule will prevent exports.', |
| 14 | + recommended: false, |
| 15 | + }, |
| 16 | + messages: { |
| 17 | + unexpectedExport: `Do not export from a test file.`, |
| 18 | + }, |
| 19 | + type: 'suggestion', |
| 20 | + schema: [], |
| 21 | + }, |
| 22 | + defaultOptions: [], |
| 23 | + create(context) { |
| 24 | + const exportNodes: Array< |
| 25 | + | TSESTree.ExportNamedDeclaration |
| 26 | + | TSESTree.ExportDefaultDeclaration |
| 27 | + | TSESTree.MemberExpression |
| 28 | + > = []; |
| 29 | + let hasTestCase = false; |
| 30 | + |
| 31 | + return { |
| 32 | + 'Program:exit'() { |
| 33 | + if (hasTestCase && exportNodes.length > 0) { |
| 34 | + for (const node of exportNodes) { |
| 35 | + context.report({ node, messageId: 'unexpectedExport' }); |
| 36 | + } |
| 37 | + } |
| 38 | + }, |
| 39 | + |
| 40 | + CallExpression(node) { |
| 41 | + if (isTestCase(node)) { |
| 42 | + hasTestCase = true; |
| 43 | + } |
| 44 | + }, |
| 45 | + 'ExportNamedDeclaration, ExportDefaultDeclaration'( |
| 46 | + node: |
| 47 | + | TSESTree.ExportNamedDeclaration |
| 48 | + | TSESTree.ExportDefaultDeclaration, |
| 49 | + ) { |
| 50 | + exportNodes.push(node); |
| 51 | + }, |
| 52 | + 'AssignmentExpression > MemberExpression'( |
| 53 | + node: TSESTree.MemberExpression, |
| 54 | + ) { |
| 55 | + let { object, property } = node; |
| 56 | + |
| 57 | + if (object.type === AST_NODE_TYPES.MemberExpression) { |
| 58 | + ({ object, property } = object); |
| 59 | + } |
| 60 | + |
| 61 | + if ( |
| 62 | + 'name' in object && |
| 63 | + object.name === 'module' && |
| 64 | + property.type === AST_NODE_TYPES.Identifier && |
| 65 | + /^exports?$/.test(property.name) |
| 66 | + ) { |
| 67 | + exportNodes.push(node); |
| 68 | + } |
| 69 | + }, |
| 70 | + }; |
| 71 | + }, |
| 72 | +}); |
0 commit comments