国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Take a snapshot
Now, let's test the DOM elements and events
This is just one way to test in React
Home Web Front-end CSS Tutorial Getting Started with React Testing Library

Getting Started with React Testing Library

Apr 21, 2025 am 09:45 AM

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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

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.

How to use Lotties in Figma How to use Lotties in Figma Jun 14, 2025 am 10:17 AM

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

Breaking Boundaries: Building a Tangram Puzzle With (S)CSS Breaking Boundaries: Building a Tangram Puzzle With (S)CSS Jun 13, 2025 am 11:33 AM

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

External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

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

Does my CSS must be on lower case? Does my CSS must be on lower case? Jun 19, 2025 am 12:29 AM

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

CSS Case Sensitivity: Understanding What Matters CSS Case Sensitivity: Understanding What Matters Jun 20, 2025 am 12:09 AM

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

What is Autoprefixer and how does it work? What is Autoprefixer and how does it work? Jul 02, 2025 am 01:15 AM

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.

What are CSS counters? What are CSS counters? Jun 19, 2025 am 12:34 AM

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

See all articles