APIs of React Testing Library

APIs of React Testing Library

Getting started with React Testing Library for unit testing

In this tutorial, we are going to learn what is React Testing Library and provide some context to the entire tutorial.

=> APIs of React Testing Library

We will look into the overview of apis of react testing library - render, cleanup, act

Render api of react testing library

In this tutorial, we will go through the get, query and find apis of the render method of the react testing library.

There are three main apis of react testing library

  • render
  • cleanup
  • act

We will focus on first api most of the time. The explanation of cleanup and act is given at the end of this tutorial.

Overview of Render API

Render API is used to render the test component. It accepts the component as first argument and returns helper methods to test the component.

const wrapper = render(<Sample/>);

Render API accepts another argument which controls the way we render the component.

const wrapper = render(<Sample/>, {
  // options here
})

default options are as follows

const wrapper = render(<Sample/>, {
  container: document.body.appendChild(document.createElement('div')),
  hydrate: false,
  wrapper: null,
  queries: <Queries from @testing-library/dom based on the baseElement>
})

Passing baseElement is of no use in the options, as the baseElement is derived from container or it defaults to document.body. Read below to understand more.
Both the options of baseElement and container is very confusing. You can visualize it as follows

  • If container is not specified
baseElement = document.body
container = baseElement + <div/>
Test component
  • If container is specified then baseElement is same as container.
baseElement = container
container = container
Test component
  • You cannot specify baseElement directly. You can change baseElement by specifying container. Either the baseElement defaults to document.body or equals to container if container is specified.

Then you may ask, what is the use of baseElement? Well, the baseElement is used when you debug the element. baseElement is the element on which all the queries are run.

Overview of act api

This is a light wrapper around the react-dom/test-utils act function. All it does is forward all arguments to the act function if your version of react supports act

Overview of cleanup api

Unmounts React trees that were mounted with render. For testing frameworks such as Jest, this is done automatically in afterEach block. The testing framework that do not have such methods, this cleanup needs to be done manually.
Below is an example of ava test framework, which does not have the afterEach block. So here we have to do the cleanup ourselves as follows.

import { cleanup, render } from '@testing-library/react'
import test from 'ava'

test.afterEach(cleanup)

test('renders into document', () => {
  render(<div />)
  // ...
})

Leave a Reply

%d bloggers like this: