no-module-exports

Try in Playground
jestjsError ProneWarning

0

No tags

No CWE or CVE

This rule aims to eliminate duplicate runs of tests by exporting things from test files.

If you import from a test file, then all the tests in that file will be run in each imported instance, so the bottom line, don't export from a test.

Instead, you should move these helper functions into a separate file where they can then be shared across tests.

View a similar ESLint rule, no-export.

Ast Rule: assignment


no-module-exports

How to write a rule
function visit(node, filename, code) {
  // only run on .spec. or .test. files
  if (!filename.includes(".spec.") && !filename.includes(".test.")) return;

  const parent = node?.left?.parent;
  const name = node?.left?.name;

  if (!parent || !name || node.left.astType !== "member") return;

  if (!parent?.value?.includes("module")) return;
  if (!name?.value?.includes("exports")) return;


  const error = buildError(
    node.left.start.line,
    node.left.start.col,
    node.left.end.line,
    node.left.end.col,
    `Disallow using 'module.exports' in files containing tests`,
    "WARNING",
    "ERROR_PRONE"
  );

  addError(error);
}

no-exports.spec.js

Expected test result: no error

Not exporting from a test file

describe('a test', () => {
  expect(1).toBe(1);
});

bad-export.test.js

Expected test result: has error

Exporting from a test file

module.exports = function () {};

module.exports = {
  something: 'that should be moved to a non-test file',
};

describe('a test', () => {
  expect(1).toBe(1);
});
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.