Getting Started with React Testing Library
You might be wondering: Another React test library? So much has been covered on CSS-Tricks (in fact, I have posted an article about Jest and Enzyme), aren't there enough options?
However, react-testing-library is more than just another test library. It's a test library, yes, but it's built on a fundamental principle, which makes it different from other test libraries.
The more your tests simulate how the software is used, the greater the confidence they can bring you.
It tries to test how users use your app. In fact, it is implemented so that even if you refactor the components, the tests will not break. I know we've had this happening at some point on our React journey.
We'll spend some time together writing tests for a simple to-do application I built using react-testing-library. You can clone the repository locally:
git clone https://github.com/kinsomicrote/todoapp-test.git
If you do this, install the required packages:
## yarn yarn add --dev react-testing-library jest-dom ## npm npm install --save-dev react-testing-library jest-dom
If you want to know why Jest is here, we use it for assertions. Create a folder named __test__
in the src directory and create a new file named App.test.js
Take a snapshot
Snapshot tests record tests performed on tested components as a way to visually view the differences between changes.
When we first run this test, we take the first snapshot of the appearance of the component. So the first test will definitely pass, because there is no other snapshot to compare to that to indicate that something fails. It fails only when we make new changes to the component by adding new elements, classes, components, or text. Add content that did not exist when the snapshot was created or when the last update was last updated.
Snapshot testing will be the first test we have written here. Let's open the App.test.js
file and make it look like this:
import React from 'react'; import { render, cleanup } from "react-testing-library"; import "jest-dom/extend-expect"; import App from './App'; afterEach(cleanup); it("matches snapshot", () => { const { asFragment } = render(<app></app> ); expect(asFragment()).toMatchSnapshot(); });
This imports the necessary packages we use to write and run tests. render
is used to display the components we want to test. We use cleanup
to clear the content after each test run - as you can see in afterEach(cleanup)
line.
Using asFragment
, we get DocumentFragment
of the render component. We then expect it to match the snapshot that has been created.
Let's run the test to see what happens:
## yarn yarn test ## npm npm test
As we now know, if this is our first test, a component snapshot is created in a new folder named __snapshots__
inside the __tests__
directory. We will actually get a file called App.test.js.snap
in it and it looks like this:
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`matches snapshot 1`] = ` <documentfragment><div> <div> <div> <h2> Add Todo </h2> </div> </div> <div> <div> </div> </div> <div> <div> Add Task </div> </div> <div> <div> <h3> Lists </h3> <ul data-test=""> <li> <div> Buy Milk X </div> </li> <li> <div> Write tutorial X </div> </li> </ul> </div> </div> </div> </documentfragment> `;
Now, let's test the DOM elements and events
Our application contains two to-do items that are displayed by default when the application is first run. We want to make sure they do show up when the first application runs, so in order to test this we have to locate the unordered list (<ul></ul>
) and check the length. We expect the length to be equal to 2 - the number of items.
it('it displays default todo items', () => { const { getByTestId } = render(<app></app> ); const todoList = getByTestId('todos-ul'); expect(todoList.children.length).toBe(2); });
We use getByTestId
in this code snippet to extract the test ID from App
component. Then we set todoList
to locate todos-ul
element. This should return 2.
Using what we have learned so far, see if you can write a test that asserts that the user can enter values in the input field. Here are the actions you need to do:
- Get input fields
- Set values for input fields
- Trigger change event
- Assert that the value of the input field is the same as the value you set for it in step 2
Don't peek at my answer below! Spend as much time as possible.
Still continuing? marvelous! I'll go have a cup of coffee and come back soon.
Well, coffee. ☕️
Oh, you're done! you are awesome. Let's compare the answers. Mine looks like this:
it('allows input', () => { const { getByTestId, fireEvent } = render(<app></app> ); let item = 'Learn React'; const todoInputElement = getByTestId('todo-input'); todoInputElement.value = item; fireEvent.change(todoInputElement); expect(todoInputElement.value).toBe('Learn React'); });
Using getByTestId
, I was able to extract the test ID in the application. Then I create a variable, set it to the string "Learn React", and make it the value of the input field. Next, I use its test ID to get the input field and trigger the change event after setting the value of the input field. After doing this, I assert that the value of the input field is indeed "Learn React".
Is this consistent with your answer? If you have other methods, please leave a comment!
Next, let's test if we can add new to-do items. We will need to get the input fields, the button to add a new project, and the unordered list, because these are all the elements needed to create a new project.
We set a value for the input field and then trigger the button click to add the task. We can do this by using getByText
to get the button - by triggering the click event on the DOM element with the text "Add Task", we should be able to add a new to-do item.
Let's assert that the number of child elements (list items) in an unordered list element is equal to 3. This assumes that the default task is still intact.
it('adds a new todo item', () => { const { getByText, getByTestId, fireEvent } = render(<app></app> ); const todoInputElement = getByTestId('todo-input'); const todoList = getByTestId('todos-ul'); todoInputElement.value = 'Learn React'; fireEvent.change(todoInputElement); fireEvent.click(getByText('Add Task')); expect(todoList.children.length).toBe(3); });
Very good, right?
This is just one way to test in React
You can try react-testing-library in the next React application. Documentation in the warehouse is very detailed and – like most tools – is the best place to start. Kent C. Dodds built it and there is a full course on testing on Frontend Masters (requires a subscription), which also covers the ins and outs of react-testing-library.
That is, this is just a test resource for React. Of course there are other resources, but hopefully you have seen some content now and are interested in giving it a try, and of course you should also use the resources that are best for your project.
The above is the detailed content of Getting Started with React Testing Library. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...
