no-mocks-require

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: function call


no-mocks-require

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;

  const isRequire = node.functionName?.value?.includes("require")
  if (!isRequire) return;

  if (node.arguments && node.arguments.values && node.arguments.values.length === 1) {
    
		const value = node.arguments.values[0].value

    if (!value?.value || !value.value.includes(MOCK_FOLDER)) return;

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

    addError(error)
  }
}

bad-mock-require.spec.js

Expected test result: has error

Requiring mocks directly

jest.mock('./x');
jest.mock('./thing');
const x = require('./__mocks__/x');
const thing = require('./__mocks__/x');

require('./__mocks__/index');
require('__mocks__');

good-mock-require.test.js

Expected test result: no error

Requiring the module and not the mocks directly

jest.mock('./x');
jest.mock('./thing');
const x = require('./x');
const thing = require('./thing');
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.