Socket
Socket
Sign inDemoInstall

eslint-plugin-testing-library

Package Overview
Dependencies
124
Maintainers
3
Versions
154
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    eslint-plugin-testing-library

ESLint rules for Testing Library


Version published
Maintainers
3
Created

Package description

What is eslint-plugin-testing-library?

The eslint-plugin-testing-library package is an ESLint plugin that provides linting rules for writing tests with the Testing Library, which is a set of utilities for testing UI components in a user-centric way. This plugin helps enforce best practices and eliminate common mistakes when writing tests with Testing Library.

What are eslint-plugin-testing-library's main functionalities?

Enforce consistent usage of Testing Library queries

This rule enforces the use of the `screen` object for querying DOM elements, which provides better consistency and avoids destructuring render result.

/* eslint testing-library/prefer-screen-queries: 'error' */
// Bad
const { getByText } = render(<App />);
getByText('Hello World');

// Good
const screen = render(<App />);
screen.getByText('Hello World');

Avoid using container methods

This rule prevents direct DOM manipulation by avoiding the use of the `container` method, encouraging the use of queries provided by Testing Library instead.

/* eslint testing-library/no-container: 'error' */
// Bad
const { container } = render(<App />);
container.querySelector('.my-class');

// Good
const { getByClassName } = render(<App />);
getByClassName('my-class');

Ensure async queries are awaited

This rule ensures that asynchronous queries like `findBy*` are properly awaited or returned in tests, which is necessary for correct test execution.

/* eslint testing-library/await-async-query: 'error' */
// Bad
getByText('Loading...');

// Good
await findByText('Loaded');

Prevent the use of debug

This rule warns or errors when the `debug` function is used, as it's intended for debugging purposes and should not be left in the final test code.

/* eslint testing-library/no-debug: 'warn' */
// Bad
const { debug } = render(<App />);
debug();

// Good
// No debug usage

Other packages similar to eslint-plugin-testing-library

Readme

Source

eslint-plugin-testing-library

ESLint plugin to follow best practices and anticipate common mistakes when writing tests with Testing Library


Build status Package version eslint-remote-tester eslint-plugin-testing-library MIT License
semantic-release PRs Welcome All Contributors
Watch on Github Star on Github Tweet

Installation

You'll first need to install ESLint:

$ npm install --save-dev eslint
# or
$ yarn add --dev eslint

Next, install eslint-plugin-testing-library:

$ npm install --save-dev eslint-plugin-testing-library
# or
$ yarn add --dev eslint-plugin-testing-library

Note: If you installed ESLint globally (using the -g flag) then you must also install eslint-plugin-testing-library globally.

Migrating

You can find detailed guides for migrating eslint-plugin-testing-library in the migration guide docs:

Usage

Add testing-library to the plugins section of your .eslintrc configuration file. You can omit the eslint-plugin- prefix:

{
	"plugins": ["testing-library"]
}

Then configure the rules you want to use within rules property of your .eslintrc:

{
	"rules": {
		"testing-library/await-async-query": "error",
		"testing-library/no-await-sync-query": "error",
		"testing-library/no-debugging-utils": "warn",
		"testing-library/no-dom-import": "off"
	}
}

Run the plugin only against test files

With the default setup mentioned before, eslint-plugin-testing-library will be run against your whole codebase. If you want to run this plugin only against your tests files, you have the following options:

ESLint overrides

One way of restricting ESLint config by file patterns is by using ESLint overrides.

Assuming you are using the same pattern for your test files as Jest by default, the following config would run eslint-plugin-testing-library only against your test files:

// .eslintrc
{
	// 1) Here we have our usual config which applies to the whole project, so we don't put testing-library preset here.
	extends: ['airbnb', 'plugin:prettier/recommended'],

	// 2) We load other plugins than eslint-plugin-testing-library globally if we want to.
	plugins: ['react-hooks'],

	overrides: [
		{
			// 3) Now we enable eslint-plugin-testing-library rules or preset only for matching testing files!
			files: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'],
			extends: ['plugin:testing-library/react'],
		},
	],
}
ESLint Cascading and Hierarchy

Another approach for customizing ESLint config by paths is through ESLint Cascading and Hierarchy. This is useful if all your tests are placed under the same folder, so you can place there another .eslintrc where you enable eslint-plugin-testing-library for applying it only to the files under such folder, rather than enabling it on your global .eslintrc which would apply to your whole project.

Shareable configurations

This plugin exports several recommended configurations that enforce good practices for specific Testing Library packages. You can find more info about enabled rules in the Supported Rules section, under the Configurations column.

Since each one of these configurations is aimed at a particular Testing Library package, they are not extendable between them, so you should use only one of them at once per .eslintrc file. For example, if you want to enable recommended configuration for React, you don't need to combine it somehow with DOM one:

// ❌ Don't do this
{
	extends: ['plugin:testing-library/dom', 'plugin:testing-library/react'],
}
// ✅ Just do this instead
{
	extends: ['plugin:testing-library/react'],
}

DOM Testing Library

Enforces recommended rules for DOM Testing Library.

To enable this configuration use the extends property in your .eslintrc config file:

{
	"extends": ["plugin:testing-library/dom"]
}

Angular

Enforces recommended rules for Angular Testing Library.

To enable this configuration use the extends property in your .eslintrc config file:

{
	"extends": ["plugin:testing-library/angular"]
}

React

Enforces recommended rules for React Testing Library.

To enable this configuration use the extends property in your .eslintrc config file:

{
	"extends": ["plugin:testing-library/react"]
}

Vue

Enforces recommended rules for Vue Testing Library.

To enable this configuration use the extends property in your .eslintrc config file:

{
	"extends": ["plugin:testing-library/vue"]
}

Marko

Enforces recommended rules for Marko Testing Library.

To enable this configuration use the extends property in your .eslintrc config file:

{
	"extends": ["plugin:testing-library/marko"]
}

Supported Rules

Remember that all rules from this plugin are prefixed by "testing-library/"

Key: 🔧 = fixable

Configurations: dom-badge = dom, angular-badge = angular, react-badge = react, vue-badge = vue, marko-badge = marko

NameDescription🔧Included in configurations
await-async-queryEnforce promises from async queries to be handleddom-badge angular-badge react-badge vue-badge marko-badge
await-async-utilsEnforce promises from async utils to be awaited properlydom-badge angular-badge react-badge vue-badge marko-badge
await-fire-eventEnforce promises from fireEvent methods to be handledvue-badge marko-badge
consistent-data-testidEnsures consistent usage of data-testid
no-await-sync-eventsDisallow unnecessary await for sync events
no-await-sync-queryDisallow unnecessary await for sync queriesdom-badge angular-badge react-badge vue-badge marko-badge
no-containerDisallow the use of container methodsangular-badge react-badge vue-badge marko-badge
no-debugging-utilsDisallow the use of debugging utilities like debugangular-badge react-badge vue-badge marko-badge
no-dom-importDisallow importing from DOM Testing Library🔧angular-badge react-badge vue-badge marko-badge
no-global-regexp-flag-in-queryDisallow the use of the global RegExp flag (/g) in queries🔧
no-manual-cleanupDisallow the use of cleanup
no-node-accessDisallow direct Node accessangular-badge react-badge vue-badge marko-badge
no-promise-in-fire-eventDisallow the use of promises passed to a fireEvent methoddom-badge angular-badge react-badge vue-badge marko-badge
no-render-in-setupDisallow the use of render in testing frameworks setup functionsangular-badge react-badge vue-badge marko-badge
no-unnecessary-actDisallow wrapping Testing Library utils or empty callbacks in actreact-badge marko-badge
no-wait-for-empty-callbackDisallow empty callbacks for waitFor and waitForElementToBeRemoveddom-badge angular-badge react-badge vue-badge marko-badge
no-wait-for-multiple-assertionsDisallow the use of multiple expect calls inside waitFordom-badge angular-badge react-badge vue-badge marko-badge
no-wait-for-side-effectsDisallow the use of side effects in waitFordom-badge angular-badge react-badge vue-badge marko-badge
no-wait-for-snapshotEnsures no snapshot is generated inside of a waitFor calldom-badge angular-badge react-badge vue-badge marko-badge
prefer-explicit-assertSuggest using explicit assertions rather than standalone queries
prefer-find-bySuggest using find(All)By* query instead of waitFor + get(All)By* to wait for elements🔧dom-badge angular-badge react-badge vue-badge marko-badge
prefer-presence-queriesEnsure appropriate get*/query* queries are used with their respective matchersdom-badge angular-badge react-badge vue-badge marko-badge
prefer-query-by-disappearanceSuggest using queryBy* queries when waiting for disappearancedom-badge angular-badge react-badge vue-badge marko-badge
prefer-screen-queriesSuggest using screen while queryingdom-badge angular-badge react-badge vue-badge marko-badge
prefer-user-eventSuggest using userEvent over fireEvent for simulating user interactions
prefer-wait-forUse waitFor instead of deprecated wait methods🔧
render-result-naming-conventionEnforce a valid naming for return value from renderangular-badge react-badge vue-badge marko-badge

Aggressive Reporting

In v4 this plugin introduced a new feature called "Aggressive Reporting", which intends to detect Testing Library utils usages even if they don't come directly from a Testing Library package (i.e. using a custom utility file to re-export everything from Testing Library). You can read more about this feature here.

If you are looking to restricting or switching off this feature, please refer to the Shared Settings section to do so.

Shared Settings

There are some configuration options available that will be shared across all the plugin rules. This is achieved using ESLint Shared Settings. These Shared Settings are meant to be used if you need to restrict or switch off the Aggressive Reporting, which is an out of the box advanced feature to lint Testing Library usages in a simpler way for most of the users. So please before configuring any of these settings, read more about the advantages of eslint-plugin-testing-library Aggressive Reporting feature, and how it's affected by these settings.

If you are sure about configuring the settings, these are the options available:

testing-library/utils-module

The name of your custom utility file from where you re-export everything from the Testing Library package, or "off" to switch related Aggressive Reporting mechanism off. Relates to Aggressive Imports Reporting.

// .eslintrc
{
	settings: {
		'testing-library/utils-module': 'my-custom-test-utility-file',
	},
}

You can find more details about the utils-module setting here.

testing-library/custom-renders

A list of function names that are valid as Testing Library custom renders, or "off" to switch related Aggressive Reporting mechanism off. Relates to Aggressive Renders Reporting.

// .eslintrc
{
	settings: {
		'testing-library/custom-renders': ['display', 'renderWithProviders'],
	},
}

You can find more details about the custom-renders setting here.

testing-library/custom-queries

A list of query names/patterns that are valid as Testing Library custom queries, or "off" to switch related Aggressive Reporting mechanism off. Relates to Aggressive Reporting - Queries

// .eslintrc
{
	settings: {
		'testing-library/custom-queries': ['ByIcon', 'getByComplexText'],
	},
}

You can find more details about the custom-queries setting here.

Switching all Aggressive Reporting mechanisms off

Since each Shared Setting is related to one Aggressive Reporting mechanism, and they accept "off" to opt out of that mechanism, you can switch the entire feature off by doing:

// .eslintrc
{
	settings: {
		'testing-library/utils-module': 'off',
		'testing-library/custom-renders': 'off',
		'testing-library/custom-queries': 'off',
	},
}

Troubleshooting

Errors reported in non-testing files

If you find ESLint errors related to eslint-plugin-testing-library in files other than testing, this could be caused by Aggressive Reporting.

You can avoid this by:

  1. running eslint-plugin-testing-library only against testing files
  2. limiting the scope of Aggressive Reporting through Shared Settings
  3. switching Aggressive Reporting feature off

If you think the error you are getting is not related to this at all, please fill a new issue with as many details as possible.

False positives in testing files

If you are getting false positive ESLint errors in your testing files, this could be caused by Aggressive Reporting.

You can avoid this by:

  1. limiting the scope of Aggressive Reporting through Shared Settings
  2. switching Aggressive Reporting feature off

If you think the error you are getting is not related to this at all, please fill a new issue with as many details as possible.

Other documentation

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Mario Beltrán Alarcón

💻 📖 👀 ⚠️ 🚇 🐛

Thomas Lombart

💻 📖 👀 ⚠️ 🚇

Ben Monro

💻 📖 ⚠️

Nicola Molinari

💻 ⚠️ 📖 👀

Aarón García Hervás

📖

Matej Šnuderl

🤔 📖

Adrià Fontcuberta

💻 ⚠️

Jon Aldinger

📖

Thomas Knickman

💻 📖 ⚠️

Kevin Sullivan

📖

Jakub Jastrzębski

💻 📖 ⚠️

Nikolay Stoynov

📖

marudor

💻 ⚠️

Tim Deschryver

💻 📖 🤔 👀 ⚠️ 🐛 🚇 📦

Tobias Deekens

🐛

Victor Cordova

💻 ⚠️ 🐛

Dmitry Lobanov

💻 ⚠️

Kent C. Dodds

🐛

Gonzalo D'Elia

💻 ⚠️ 📖 👀

Jeff Rifwald

📖

Leandro Lourenci

🐛 💻 ⚠️

Miguel Erja González

🐛

Pavel Pustovalov

🐛

Jacob Parish

🐛 💻 ⚠️

Nick McCurdy

🤔 💻 👀

Stefan Cameron

🐛

Mateus Felix

💻 ⚠️ 📖

Renato Augusto Gama dos Santos

🤔 💻 📖 ⚠️

Josh Kelly

💻

Alessia Bellisario

💻 ⚠️ 📖

Spencer Miskoviak

💻 ⚠️ 📖 🤔

Giorgio Polvara

💻 ⚠️ 📖

Josh David

📖

Michaël De Boey

💻 📦 🚧 🚇 👀

Jian Huang

💻 ⚠️ 📖

Philipp Fritsche

💻

Tomas Zaicevas

🐛 💻 ⚠️ 📖

Gareth Jones

💻 📖 ⚠️

HonkingGoose

📖 🚧

Julien Wajsberg

🐛 💻 ⚠️

Marat Dyatko

🐛 💻

David Tolman

🐛

Ari Perkkiö

⚠️

Diego Castillo

💻

Bruno Pinto

💻 ⚠️

themagickoala

💻 ⚠️

Prashant Ashok

💻 ⚠️

Ivan Aprea

💻 ⚠️

Dmitry Semigradsky

💻 ⚠️ 📖

Senja

💻 ⚠️ 📖

Breno Cota

💻 ⚠️

This project follows the all-contributors specification. Contributions of any kind welcome!

Keywords

FAQs

Last updated on 02 Oct 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc