no-dom-import

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-import)

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: import


no-dom-import

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

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

  if (
    node.pkg &&
    (
      cleanName(node.pkg.value) === "dom-testing-library" ||
      cleanName(node.pkg.value) === "@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

import { fireEvent } from "dom-testing-library";
import { fireEvent } from '@testing-library/dom';

import { render } from '@testing-library/react'; // Okay, no error
import { screen } from '@testing-library/dom'; // Error, unnecessary import from @testing-library/dom

test.spec.js

Expected test result: no error

Examples of correct code for this rule


import { fireEvent } from 'react-testing-library';
import { fireEvent } from '@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.