Configurations
Even Though React Testing Library does not require you to use any configuration, there are some things you can do to configure your testing framework and reduce some boilerplate.
Although this article uses Jest, It is worth noting that you can perform similar configurations using any testing framework as RTL does not require you to use Jest.
Custom Render
Defining a custom render method, including global context providers, data stores, etc., is often helpful when writing test cases. You can specify a utility file that re-exports everything from React Testing Library and replace React Testing Library with that file in all your imports to achieve this.
// instead of [ import { render, fireEvent } from '@testing-library/react'; ]
import { render, fireEvent } from '../test-utils'
The following example sets up data providers using the wrapper option to render.
Program
// test-utils.jsx
import React from 'react'
import {render} from '@testing-library/react'
import {ThemeProvider} from 'my-ui-lib'
import {TranslationProvider} from 'my-i18n-lib'
import defaultStrings from 'i18n/en-x-default'
const AllTheProviders = ({children}) => {
return (
<ThemeProvider theme="light">
<TranslationProvider messages={defaultStrings}>
{children}
</TranslationProvider>
</ThemeProvider>
)
}
const customRender = (ui, options) =>
render(ui, {wrapper: AllTheProviders, ...options})
// re-export everything
export * from '@testing-library/react'
// override render method
export {customRender as render}
Instead of ES modules, you can use CommonJS modules for Babel versions six and below.
Custom Queries
After defining your custom queries, you can use custom queries in any render call using the queries option. You can explore the Custom Queries documentation for in-depth specifications. You can add custom queries to your custom render method to make them globally available.
Here, we create a new set of query variants for getting elements by data-cy, a "test ID" convention.
Program
// custom-queries.js
import { queryHelpers, buildQueries } from "@testing-library/react";
// queryAllByAttribute is a shortcut for attribute-based matchers
// We can also use document.querySelector or an existing combination
// testing library utilities for finding matching nodes for your query
const queryAllByDataCy = (...args) =>
queryHelpers.queryAllByAttribute("data-cy", ...args);
const getMultipleError = (c, dataCyValue) =>
`Finds multiple elements with the data-cy attribute of: ${dataCyValue}`;
const getMissingError = (c, dataCyValue) =>
`Can not find an element with the data-cy attribute of: ${dataCyValue}`;
const [
queryByDataCy,
getAllByDataCy,
getByDataCy,
findAllByDataCy,
findByDataCy,
] = buildQueries(queryAllByDataCy, getMultipleError, getMissingError);
export {
queryByDataCy,
queryAllByDataCy,
getByDataCy,
getAllByDataCy,
findAllByDataCy,
findByDataCy,
};
const AllTheProviders = ({children}) => {
return (
<ThemeProvider theme="light">
<TranslationProvider messages={defaultStrings}>
{children}
</TranslationProvider>
</ThemeProvider>
)
}
Now you can define a custom render method in your test-utils and override or append new queries by passing a queries option using the render function.
Program
// test-utils.js
import {render, queries} from '@testing-library/react'
import * as customQueries from './custom-queries'
const customRender = (ui, options) =>
render(ui, {queries: {...queries, ...customQueries}, ...options})
// re-export everything
export * from '@testing-library/react'
// override render method
export {customRender as render}
That makes it very easy to access custom queries as you would any other query.
Program
const { getByDataCy } = render(<Component />);
expect(getByDataCy("my-component")).toHaveTextContent("Hello");
Configuring Jest
Using the Jest framework for testing, you can configure it with Test Utils. If you want to make your custom test accessible in your Jest test files without using relative imports(../../test-utils), you can add the test file folder to the Jest moduleDirectories option.
Program
// jest.config.js
module.exports = {
moduleDirectories: [
"node_modules",
+(
// the directory with the test-utils.js file
//example
(+"utils")
), // a utility folder
+__dirname, // the root directory
],
// ... options ...
};
This will make all the test-utils directory's .js files importable without relative path.
// import { render, fireEvent } from '../test-utils';
import { render, fireEvent } from 'test-utils'
Frequently Asked Questions
-
Can you use React Testing Library without Jest?
The React Testing Library is an excellent library that is easy to use and promotes better testing practices. You do not require Jest necessarily to use RTL, and you can use other frameworks like Mocha, Enzyme, Chai, etc. The choice of the testing framework should depict the need and behavior of the system under test.
-
Where do you put a React test?
The recommended method of saving your test file is in a folder named __tests__ in your project directory where you place your application. Alternatively, you can also store your test file directly in the project directory parallel to your application with the .test.js name convention. Example: App.test.js and App.js.
-
What is the difference between Jest and React Testing Library?
Jest is a test runner which allows you to run tests from the command line and offers functions for test suites, test cases, and assertions. The React Testing Library is not a test runner; it provides you the function to catch dom elements and perform actions like render, waitFor, fireEvent, etc.
React Testing Library is not an alternative or replacement to Jest because both tools need each other and have clear and specific tasks.
-
What is the best testing framework for Reactjs?
Jest is currently the most popular JavaScript unit testing framework. Jest is a highly preferred framework for web apps based on React. Apart from React, Jest also supports unit testing of Angular, VueJS, NodeJS, and others.
Conclusion
In this article, we have extensively discussed the setup of the React Testing Library and its configurations and implementation in Javascript using Jest. There are a lot more features available in RTL for you to exploit. You can try exploring this library using different test cases, testing frameworks, and versions to better grip this topic.
We hope that this blog has helped you enhance your knowledge regarding React Testing Library, and if you would like to learn more, check out our articles on React Test Utilities, React Test Renderer, and Testing React App with Jest. Do upvote our blog to help other ninjas grow. Happy Coding!