no-dom-require

Try in Playground
testing-library

oscar143

Best PracticeInformational

0

testing-library

No CWE or CVE

Disallow importing from DOM Testing Library (testing-library/no-dom-require)

Ensure that there are no direct imports from @testing-library/dom or dom-testing-library when using some testing library framework wrapper.

Rule Details

Testing Library framework wrappers as React Testing Library already re-exports everything from DOM Testing Library, so you always have to import Testing Library utils from corresponding framework wrapper module to:

  • use proper extended version of some of those methods containing additional functionality related to specific framework (e.g. fireEvent util)
  • avoid importing from extraneous dependencies (similar to eslint-plugin-import)

This rule aims to prevent users from import anything directly from @testing-library/dom, which is useful for new starters or when IDEs autoimport from wrong module.

Ast Rule: assignment


no-dom-require

How to write a rule
function cleanName(name) {
  return name.substr(1).slice(0, -1);
}

function getFirstArgumentValue(arguments) {
  if (arguments.values.length) {
    const first = arguments.values[0];

    return cleanName(first.value.value);
  }

  return "";
}

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

  if (
    node.right &&
    node.right.astType === "functioncall" &&
    node.right.functionName.astType === "string" &&
    node.right.functionName.value === "require" &&
    (
      getFirstArgumentValue(node.right.arguments) === "dom-testing-library" ||
      getFirstArgumentValue(node.right.arguments) === "@testing-library/dom"
    )
  ) {
    const error = buildError(
      node.start.line,
      node.start.col,
      node.end.line,
      node.end.col,
      "import from DOM Testing Library is restricted, import from corresponding Testing Library framework instead.",
      "INFORMATIONAL",
      "BEST_PRACTICE"
    );

    addError(error);
  }
}

test.spec.js

Expected test result: has error

Examples of incorrect code for this rule:


const { fireEvent } = require('dom-testing-library');
const { fireEvent } = require('@testing-library/dom');

test.spec.js

Expected test result: no error

Examples of correct code for this rule

const { fireEvent } = require('react-testing-library');
const { fireEvent } = require('@testing-library/react');
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.