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

Undress AI Tool
Undress images for free

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

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

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

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

In the following tutorial, I will show you how to create Lottie animations in Figma. We'll use two colorful designs to exmplify how you can animate in Figma, and then I'll show you how to go from Figma to Lottie animations. All you need is a free Fig

We put it to the test and it turns out Sass can replace JavaScript, at least when it comes to low-level logic and puzzle behavior. With nothing but maps, mixins, functions, and a whole lot of math, we managed to bring our Tangram puzzle to life, no J

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.
