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)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.
