no-mocks-import

Try in Playground
jestjsBest PracticeWarning

0

No tags

No CWE or CVE

When using jest.mock, your tests (just like the code being tested) should import from ./x, not ./__mocks__/x.

Not following this rule can lead to confusion, because you will have multiple instances of the mocked module like the test cases show.

View a similar ESLint rule, no-mocks-import.

Ast Rule: import


no-mocks-import

How to write a rule
const MOCK_FOLDER = "__mocks__"

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

  if (!node.pkg?.value) return;
  if (!node.pkg.value.includes(MOCK_FOLDER)) return;

  const error = buildError(
    node.start.line,
    node.start.col,
    node.end.line,
    node.end.col,
    `Disallow manually importing from '__mocks__'`,
    "WARNING",
    "BEST_PRACTICE"
  )

  addError(error)
}

good-mock-import.spec.js

Expected test result: no error

Importing the module and not the mocks directly

jest.mock('./x');
jest.mock('./thing');
import x from './x';
import thing from './thing';

bad-mock-import.test.js

Expected test result: has error

Importing mocks directly

jest.mock('./x');
import x1 from './x';
import x2 from './__mocks__/x';
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
Legal
  • Security
  • Privacy Policy
  • Code Privacy
  • Terms of Service
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.