eslint-plugin-testing-library
ESLint plugin to follow best practices and anticipate common mistakes when writing tests with Testing Library
Top Related Projects
ESLint plugin for Jest
React-specific linting rules for ESLint
:sparkles: Monorepo for all the tooling which enables ESLint to support TypeScript
Static AST checker for a11y rules on JSX elements.
Quick Overview
ESLint Plugin Testing Library is an ESLint plugin for Testing Library, a set of tools for testing UI components. It provides custom ESLint rules to help developers follow best practices when using Testing Library, ensuring more maintainable and reliable tests for React, Vue, and other JavaScript applications.
Pros
- Enforces best practices for Testing Library usage
- Helps catch common mistakes and anti-patterns early in the development process
- Improves test readability and maintainability
- Integrates seamlessly with existing ESLint configurations
Cons
- May require initial setup and configuration time
- Some rules might be too opinionated for certain project requirements
- Learning curve for developers unfamiliar with Testing Library best practices
- Occasional false positives or negatives in rule enforcement
Code Examples
- Using the
getBy*
query:
// Good: Using getByRole for accessibility
const button = screen.getByRole('button', { name: 'Submit' });
// Bad: Using getByTestId (discouraged)
const input = screen.getByTestId('username-input');
- Avoiding
container
queries:
// Good: Using screen queries
const heading = screen.getByText('Welcome');
// Bad: Using container queries
const paragraph = container.querySelector('p');
- Using async queries:
// Good: Using findBy for asynchronous elements
const loadedContent = await screen.findByText('Data loaded');
// Bad: Using getBy with setTimeout
setTimeout(() => {
const loadedContent = screen.getByText('Data loaded');
}, 1000);
Getting Started
To use ESLint Plugin Testing Library in your project:
- Install the plugin:
npm install --save-dev eslint-plugin-testing-library
- Add the plugin to your ESLint configuration file (e.g.,
.eslintrc.js
):
module.exports = {
plugins: ['testing-library'],
extends: [
'plugin:testing-library/react', // Or 'vue', 'angular', etc.
],
};
- Run ESLint on your test files to start enforcing Testing Library best practices.
Competitor Comparisons
ESLint plugin for Jest
Pros of eslint-plugin-jest
- Broader coverage of Jest-specific rules and best practices
- Larger community and more frequent updates
- Includes rules for Jest-specific APIs and globals
Cons of eslint-plugin-jest
- Less focus on general testing best practices
- May require additional configuration for non-Jest testing frameworks
- Some rules might be too opinionated for certain projects
Code Comparison
eslint-plugin-jest:
// Valid
test('addition', () => {
expect(1 + 2).toBe(3);
});
// Invalid (no-identical-title rule)
test('foo', () => {});
test('foo', () => {});
eslint-plugin-testing-library:
// Valid
const { getByText } = render(<MyComponent />);
expect(getByText('Hello')).toBeInTheDocument();
// Invalid (await-async-query rule)
const element = getByText('Hello');
Both plugins aim to improve test quality, but eslint-plugin-jest focuses on Jest-specific patterns, while eslint-plugin-testing-library emphasizes best practices for DOM testing and query usage. eslint-plugin-jest offers more comprehensive coverage for Jest users, including rules for test structure and Jest API usage. On the other hand, eslint-plugin-testing-library provides valuable guidance for using Testing Library effectively, regardless of the test runner. The choice between the two depends on your testing setup and specific needs, with some projects benefiting from using both plugins together.
React-specific linting rules for ESLint
Pros of eslint-plugin-react
- Broader scope: Covers a wide range of React-specific linting rules
- Larger community and more frequent updates
- Extensive configuration options for fine-tuning rules
Cons of eslint-plugin-react
- Can be overwhelming with numerous rules to configure
- May require more setup time for optimal usage
- Some rules might conflict with newer React patterns or hooks
Code Comparison
eslint-plugin-react:
// .eslintrc.js
module.exports = {
plugins: ['react'],
rules: {
'react/jsx-uses-react': 'error',
'react/jsx-uses-vars': 'error',
},
};
eslint-plugin-testing-library:
// .eslintrc.js
module.exports = {
plugins: ['testing-library'],
rules: {
'testing-library/await-async-query': 'error',
'testing-library/no-await-sync-query': 'error',
},
};
Summary
eslint-plugin-react is a comprehensive linting tool for React projects, offering a wide range of rules and configurations. It's well-maintained and widely adopted but can be complex to set up. eslint-plugin-testing-library, on the other hand, focuses specifically on Testing Library best practices, making it more straightforward for testing-related linting but with a narrower scope. The choice between the two depends on the project's needs: general React development or Testing Library-specific practices.
:sparkles: Monorepo for all the tooling which enables ESLint to support TypeScript
Pros of typescript-eslint
- Broader scope: Provides comprehensive TypeScript linting and static analysis
- Larger community and more frequent updates
- Offers type-aware rules for enhanced code quality
Cons of typescript-eslint
- Steeper learning curve due to its extensive feature set
- May require more configuration for optimal use
- Potentially slower performance due to type checking
Code Comparison
typescript-eslint:
// @typescript-eslint/no-explicit-any
function example(param: any) {
return param;
}
eslint-plugin-testing-library:
// testing-library/no-await-sync-events
await userEvent.click(button);
typescript-eslint focuses on TypeScript-specific linting, while eslint-plugin-testing-library targets best practices for testing libraries. typescript-eslint has a wider range of rules and capabilities, making it more versatile for general TypeScript development. eslint-plugin-testing-library is more specialized, offering rules specifically tailored to improve testing practices.
typescript-eslint is essential for TypeScript projects, providing type-aware linting and helping catch type-related issues early. eslint-plugin-testing-library, on the other hand, is crucial for projects using testing libraries like React Testing Library, ensuring proper usage and best practices in test files.
Static AST checker for a11y rules on JSX elements.
Pros of eslint-plugin-jsx-a11y
- Focuses specifically on accessibility issues in JSX, providing comprehensive coverage for a11y concerns
- Has a larger user base and more frequent updates, indicating active maintenance
- Offers more rules (around 40) compared to eslint-plugin-testing-library (around 20)
Cons of eslint-plugin-jsx-a11y
- Limited to JSX and React-specific accessibility issues, less versatile for other testing scenarios
- May require more configuration to integrate with non-React projects
- Some rules might be overly strict for certain use cases, potentially leading to false positives
Code Comparison
eslint-plugin-jsx-a11y:
// eslint-disable-next-line jsx-a11y/anchor-is-valid
<a onClick={handleClick}>Click me</a>
eslint-plugin-testing-library:
// eslint-disable-next-line testing-library/no-node-access
const element = container.querySelector('.my-class');
Both plugins provide specific rules to enhance code quality, but they focus on different aspects. eslint-plugin-jsx-a11y targets accessibility in JSX, while eslint-plugin-testing-library aims to improve testing practices across various testing libraries.
eslint-plugin-jsx-a11y is more specialized for React and JSX development, offering a comprehensive set of accessibility-focused rules. On the other hand, eslint-plugin-testing-library is more versatile, applicable to various testing scenarios and libraries, but with fewer rules overall.
The choice between these plugins depends on the project's specific needs: accessibility in React applications or enforcing best practices in testing across different libraries.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME


eslint-plugin-testing-library
ESLint plugin to follow best practices and anticipate common mistakes when writing tests with Testing Library
Prerequisites
To use this plugin, you must have Node.js (^18.18.0
, ^20.9.0
, or >=21.1.0
) installed.
Installation
You'll first need to install ESLint.
Next, install eslint-plugin-testing-library
:
$ pnpm add --save-dev eslint-plugin-testing-library
# or
$ 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.js
configuration file. You can omit the eslint-plugin-
prefix:
module.exports = {
plugins: ['testing-library'],
};
Then configure the rules you want to use within rules
property of your .eslintrc
:
module.exports = {
rules: {
'testing-library/await-async-queries': 'error',
'testing-library/no-await-sync-queries': '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.js
module.exports = {
// 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
[!NOTE]
eslint.config.js
compatible versions of configs are available prefixed withflat/
, though most of the plugin documentation still currently uses.eslintrc
syntax.Refer to the ESLint documentation on the new configuration file format for more.
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
module.exports = {
extends: ['plugin:testing-library/dom', 'plugin:testing-library/react'],
};
// â
Just do this instead
module.exports = {
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.js
config file:
module.exports = {
extends: ['plugin:testing-library/dom'],
};
To enable this configuration with eslint.config.js
, use
testingLibrary.configs['flat/dom']
:
const testingLibrary = require('eslint-plugin-testing-library');
module.exports = [
{
files: [
/* glob matching your test files */
],
...testingLibrary.configs['flat/dom'],
},
];
Angular
Enforces recommended rules for Angular Testing Library.
To enable this configuration use the extends
property in your
.eslintrc.js
config file:
module.exports = {
extends: ['plugin:testing-library/angular'],
};
To enable this configuration with eslint.config.js
, use
testingLibrary.configs['flat/angular']
:
const testingLibrary = require('eslint-plugin-testing-library');
module.exports = [
{
files: [
/* glob matching your test files */
],
...testingLibrary.configs['flat/angular'],
},
];
React
Enforces recommended rules for React Testing Library.
To enable this configuration use the extends
property in your
.eslintrc.js
config file:
module.exports = {
extends: ['plugin:testing-library/react'],
};
To enable this configuration with eslint.config.js
, use
testingLibrary.configs['flat/react']
:
const testingLibrary = require('eslint-plugin-testing-library');
module.exports = [
{
files: [
/* glob matching your test files */
],
...testingLibrary.configs['flat/react'],
},
];
Vue
Enforces recommended rules for Vue Testing Library.
To enable this configuration use the extends
property in your
.eslintrc.js
config file:
module.exports = {
extends: ['plugin:testing-library/vue'],
};
To enable this configuration with eslint.config.js
, use
testingLibrary.configs['flat/vue']
:
const testingLibrary = require('eslint-plugin-testing-library');
module.exports = [
{
files: [
/* glob matching your test files */
],
...testingLibrary.configs['flat/vue'],
},
];
Svelte
Enforces recommended rules for Svelte Testing Library.
To enable this configuration use the extends
property in your
.eslintrc.js
config file:
module.exports = {
extends: ['plugin:testing-library/svelte'],
};
To enable this configuration with eslint.config.js
, use
testingLibrary.configs['flat/svelte']
:
const testingLibrary = require('eslint-plugin-testing-library');
module.exports = [
{
files: [
/* glob matching your test files */
],
...testingLibrary.configs['flat/svelte'],
},
];
Marko
Enforces recommended rules for Marko Testing Library.
To enable this configuration use the extends
property in your
.eslintrc.js
config file:
module.exports = {
extends: ['plugin:testing-library/marko'],
};
To enable this configuration with eslint.config.js
, use
testingLibrary.configs['flat/marko']
:
const testingLibrary = require('eslint-plugin-testing-library');
module.exports = [
{
files: [
/* glob matching your test files */
],
...testingLibrary.configs['flat/marko'],
},
];
Supported Rules
Remember that all rules from this plugin are prefixed by
"testing-library/"
ð¼ Configurations enabled in.
â ï¸ Configurations set to warn in.
ð§ Automatically fixable by the --fix
CLI option.
Name                           | Description | ð¼ | â ï¸ | ð§ |
---|---|---|---|---|
await-async-events | Enforce promises from async event methods are handled | ð§ | ||
await-async-queries | Enforce promises from async queries to be handled | |||
await-async-utils | Enforce promises from async utils to be awaited properly | |||
consistent-data-testid | Ensures consistent usage of data-testid | |||
no-await-sync-events | Disallow unnecessary await for sync events | |||
no-await-sync-queries | Disallow unnecessary await for sync queries | |||
no-container | Disallow the use of container methods | |||
no-debugging-utils | Disallow the use of debugging utilities like debug | |||
no-dom-import | Disallow importing from DOM Testing Library | ð§ | ||
no-global-regexp-flag-in-query | Disallow the use of the global RegExp flag (/g) in queries | ð§ | ||
no-manual-cleanup | Disallow the use of cleanup | |||
no-node-access | Disallow direct Node access | |||
no-promise-in-fire-event | Disallow the use of promises passed to a fireEvent method | |||
no-render-in-lifecycle | Disallow the use of render in testing frameworks setup functions | |||
no-unnecessary-act | Disallow wrapping Testing Library utils or empty callbacks in act | |||
no-wait-for-multiple-assertions | Disallow the use of multiple expect calls inside waitFor | |||
no-wait-for-side-effects | Disallow the use of side effects in waitFor | |||
no-wait-for-snapshot | Ensures no snapshot is generated inside of a waitFor call | |||
prefer-explicit-assert | Suggest using explicit assertions rather than standalone queries | |||
prefer-find-by | Suggest using find(All)By* query instead of waitFor + get(All)By* to wait for elements | ð§ | ||
prefer-implicit-assert | Suggest using implicit assertions for getBy* & findBy* queries | |||
prefer-presence-queries | Ensure appropriate get* /query* queries are used with their respective matchers | |||
prefer-query-by-disappearance | Suggest using queryBy* queries when waiting for disappearance | |||
prefer-query-matchers | Ensure the configured get* /query* query is used with the corresponding matchers | |||
prefer-screen-queries | Suggest using screen while querying | |||
prefer-user-event | Suggest using userEvent over fireEvent for simulating user interactions | |||
render-result-naming-convention | Enforce a valid naming for return value from render |
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.js
module.exports = {
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.js
module.exports = {
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.js
module.exports = {
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.js
module.exports = {
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:
- running
eslint-plugin-testing-library
only against testing files - limiting the scope of Aggressive Reporting through Shared Settings
- 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:
- limiting the scope of Aggressive Reporting through Shared Settings
- 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):
This project follows the all-contributors specification. Contributions of any kind welcome!
Top Related Projects
ESLint plugin for Jest
React-specific linting rules for ESLint
:sparkles: Monorepo for all the tooling which enables ESLint to support TypeScript
Static AST checker for a11y rules on JSX elements.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot