Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Setup
3.
Configurations
3.1.
Custom Render
3.1.1.
Program
3.2.
Custom Queries
3.2.1.
Program
3.2.2.
Program
3.2.3.
Program
3.3.
Configuring Jest
3.3.1.
Program
4.
Frequently Asked Questions
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

React Testing Library Setup

Introduction

React Testing Library(RTL) is a lightweight tool that you can use to test react components. RTL works by providing light utility functions on top of react-dom and react-dom/test-utils, encouraging better testing practices. To start exploiting the capabilities of RTL, you need to understand how to set it up and configure it according to your need. We will explore the setup of the React Testing Library and some configurations that you can perform while using it through this article. 

Click on the following link to read further: Hooks in React JS

Setup

Getting started with the React Testing Library is pretty straightforward if you are already familiar with the basics of React. You can check out the Basics of React article on Coding Ninjas before reading this article if you are not familiar with React.

You can set up React Testing Library along with Jest, @types/jest for type definitions of Jest for TypeScript and IDE intellisence, and Jest prettier to format inline snapshots in your node project by using the following command inside your project using the terminal.

npm install --save-dev @testing-library/react jest @types/jest prettier

 

Alternatively, you can also create a new React app using Create React App(CRA) which automatically includes both React Testing Library and Jest by default.

npx create-react-app test-example

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 providersdata 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

  1.  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.

     
  2. 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.

     
  3.  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.

     
  4. 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 UtilitiesReact Test Renderer, and Testing React App with Jest. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass