search
HomeWeb Front-endCSS TutorialGetting Started with React Testing Library

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Simulating Mouse MovementSimulating Mouse MovementApr 22, 2025 am 11:45 AM

If you've ever had to display an interactive animation during a live talk or a class, then you may know that it's not always easy to interact with your slides

Powering Search With Astro Actions and Fuse.jsPowering Search With Astro Actions and Fuse.jsApr 22, 2025 am 11:41 AM

With Astro, we can generate most of our site during our build, but have a small bit of server-side code that can handle search functionality using something like Fuse.js. In this demo, we’ll use Fuse to search through a set of personal “bookmarks” th

Undefined: The Third Boolean ValueUndefined: The Third Boolean ValueApr 22, 2025 am 11:38 AM

I wanted to implement a notification message in one of my projects, similar to what you’d see in Google Docs while a document is saving. In other words, a

In Defense of the Ternary StatementIn Defense of the Ternary StatementApr 22, 2025 am 11:25 AM

Some months ago I was on Hacker News (as one does) and I ran across a (now deleted) article about not using if statements. If you’re new to this idea (like I

Using the Web Speech API for Multilingual TranslationsUsing the Web Speech API for Multilingual TranslationsApr 22, 2025 am 11:23 AM

Since the early days of science fiction, we have fantasized about machines that talk to us. Today it is commonplace. Even so, the technology for making

Jetpack Gutenberg BlocksJetpack Gutenberg BlocksApr 22, 2025 am 11:20 AM

I remember when Gutenberg was released into core, because I was at WordCamp US that day. A number of months have gone by now, so I imagine more and more of us

Creating a Reusable Pagination Component in VueCreating a Reusable Pagination Component in VueApr 22, 2025 am 11:17 AM

The idea behind most of web applications is to fetch data from the database and present it to the user in the best possible way. When we deal with data there

Using 'box shadows' and clip-path togetherUsing 'box shadows' and clip-path togetherApr 22, 2025 am 11:13 AM

Let's do a little step-by-step of a situation where you can't quite do what seems to make sense, but you can still get it done with CSS trickery. In this

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function