React Testing Checklist
React Testing Checklist
React Testing Checklist
1
Use it to make sure that your React components are tested thoroughly.
TLDR
To make it easier to manage your tests organize them using the describe
blocks.
Every if, && and cond ? x : y in your layout signals that you have a
condition. Create a separate describe block for each value that is used in
those conditions.
Each callback function requires a describe block.
Make dependencies explicit by defining them as props with default values.
You can plan the tests before writing them using the it.todo syntax. This way
you can temporarily define only the name of the test and omit the callback part.
1 describe("ComponentName", () => {
2 describe("some aspect of the tested component", () => {
3 it.todo("satisfies specific expectations")
4 })
5 })
After you plan the tests go through them and write the expectations.
ExampleComponent.spec.jsx
The describe blocks that you create for each value the flag can have can contain
multiple cases. For example your component might only render a button if some
prop is true. Then you'll write the test for the click handler of this button in the
same describe block as you used to write the rendering test.
Every condition in your component's layout requires a separate describe block
in your tests. If your test ends up having too many describe blocks for your
conditions - it's a hint that your component might be doing too many things
and should be split into multiple components.
If your component's state changes on some user action, for example button click
- click this button in your test using the fireEvent method from @testing-
library/react and then check the expectation on component render value.
If you follow the Arrange Act Assert pattern - it will just mean that your Arrange
block will become bigger.
Also same as in previous section. Create a describe block for every condition
value in your layout.
CounterComponent.jsx
CounterComponent.spec.jsx
1 import React from 'react';
2 import { CounterComponent } from './CounterComponent'
3 import { render, fireEvent, act } from '@testing-library/react'
4
5 describe("CounterComponent", () => {
6 describe("#increment", () => {
7 const { container, getByRole } = render(<CounterComponet />)
8
9 expect(container.innerHTML).toMatch("0")
10 act(() => {
11 fireEvent(getByRole("button"))
12 })
13 expect(container.innerHTML).toMatch("1")
14 })
15 })
When you perform actions that update the component state - you need to wrap
those actions into act function.
ExampleComponent.jsx
ExampleComponent.spec.jsx