Kuidas alustada React rakenduste testimist React Testing Library ja Jesti abil

Testimist peetakse sageli tüütuks protsessiks. See on lisakood, mille peate kirjutama ja mõnel juhul, ausalt öeldes, pole seda vaja. Kuid iga arendaja peaks teadma vähemalt testimise põhitõdesid. See suurendab usaldust nende loodud toodete vastu ja enamiku ettevõtete jaoks on see nõutav.

Reacti maailmas on hämmastav teek nimega, react-testing-librarymis aitab teil React rakendusi tõhusamalt testida. Sa kasutad seda koos Jestiga.

Selles artiklis näeme 8 lihtsat sammu, mille abil saate oma React Appsi ülemuse kombel testida.

  • Eeldused
  • Põhitõed
  • Mis on React Testing Library?
  • 1. Kuidas luua testi hetktõmmist?
  • 2. DOM-elementide testimine
  • 3. Sündmuste testimine
  • 4. Asünkroonsete toimingute testimine
  • 5. React Reduxi testimine
  • 6. Reageeriva konteksti testimine
  • 7. React Routeri testimine
  • 8. HTTP päringu testimine
  • Lõpumõtted
  • Järgmised sammud

Eeldused

Selles õpetuses eeldatakse, et teil on Reactist vähemalt põhiteadmised. Keskendun ainult testimisele.

Ja järgimiseks peate projekti kloonima oma terminalis käivitades:

 git clone //github.com/ibrahima92/prep-react-testing-library-guide 

Järgmisena käivitage:

 yarn 

Või kui kasutate NPM-i:

npm install 

Ja see ongi kõik! Nüüd uurime mõnda põhitõde.

Põhitõed

Mõningaid põhiasju kasutatakse selles artiklis palju ja nende rolli mõistmine aitab teil mõista.

it or test: kirjeldab testi ennast. See võtab parameetritena testi nime ja testi hoidva funktsiooni.

expect: tingimus, mille test peab läbima. See võrdleb saadud parameetrit sobitajaga.

a matcher: funktsioon, mida rakendatakse eeldatava tingimuse korral.

render: meetod, mida kasutatakse antud komponendi renderdamiseks.

import React from 'react' import {render} from '@testing-library/react' import App from './App' it('should take a snapshot', () => { const { asFragment } = render() expect(asFragment()).toMatchSnapshot() }) }); 

Nagu näete, kirjeldame testi it, seejärel kasutage renderrakenduse komponendi kuvamiseks ja eeldame, et see asFragment()sobib toMatchSnapshot()( vaste, mille pakub jest-dom).

Muide, rendermeetod tagastab mitu meetodit, mida saame kasutada oma funktsioonide testimiseks. Meetodi saamiseks kasutasime ka ümberstruktureerimist.

Nagu öeldud, jätkame ja õpime järgmises jaotises lisateavet React Testing Library kohta.

Mis on React Testing Library?

React Testing Library on väga kerge pakett, mille on loonud Kent C. Dodds. See on Ensüümi asendaja ja pakub kergeid utiliidi funktsioone peal react-domja peal react-dom/test-utils.

React Testing Library on DOM-i testimise teek, mis tähendab, et renderdatud React-komponentide eksemplaridega tegelemise asemel tegeleb see DOM-elementidega ja sellega, kuidas nad tegelike kasutajate ees käituvad.

See on suurepärane raamatukogu, seda on (suhteliselt) lihtne kasutama hakata ja see soodustab häid testimistavasid. Pange tähele - saate seda kasutada ka ilma Jestita.

"Mida rohkem teie testid sarnanevad teie tarkvara kasutamisviisiga, seda rohkem saavad nad teile enesekindlust pakkuda."

Niisiis, alustame selle kasutamist järgmises osas. Muide, te ei pea installima ühtegi paketti, kuna see create-react-appon varustatud teegi ja selle sõltuvustega.

1. Kuidas luua testi hetktõmmist

Pilt, nagu nimigi ütleb, võimaldab meil antud komponendi hetktõmmise salvestada. See aitab palju, kui värskendate või teete mõningaid refaktoreid ja soovite muudatusi saada või võrrelda.

Now, let's take a snapshot of the App.js file.

  • App.test.js
import React from 'react' import {render, cleanup} from '@testing-library/react' import App from './App' afterEach(cleanup) it('should take a snapshot', () => { const { asFragment } = render() expect(asFragment()).toMatchSnapshot() }) }); 

To take a snapshot, we first have to import render and cleanup. These two methods will be used a lot throughout this article.

render, as you might guess, helps to render a React component. And cleanup is passed as a parameter to afterEach to just clean up everything after each test to avoid memory leaks.

Next, we can render the App component with render and get back asFragment as a returned value from the method. And finally, make sure that the fragment of the App component matches the snapshot.

Now, to run the test, open your terminal and navigate to the root of the project and run the following command:

 yarn test 

Or, if you use npm:

 npm test 

As a result, it will create a new folder __snapshots__ and a file App.test.js.snap in the src which will look like this:

  • App.test.js.snap
// Jest Snapshot v1, //goo.gl/fbAQLP exports[`Take a snapshot should take a snapshot 1`] = ` 

Testing

`;

And if you make another change in App.js, the test will fail, because the snapshot will no longer match the condition. To make it passes, just press u to update it. And you'll have the updated snapshot in App.test.js.snap.

Now, let's move on and start testing our elements.

2. Testing DOM elements

To test our DOM elements, we first have to look at the TestElements.js file.

  • TestElements.js
import React from 'react' const TestElements = () => { const [counter, setCounter] = React.useState(0) return (  

{ counter }

setCounter(counter + 1)}> Up setCounter(counter - 1)}>Down ) } export default TestElements

Here, the only thing you have to retain is data-testid. It will be used to select these elements from the test file. Now, let's write the unit test:

Test if the counter is equal to 0:

TestElements.test.js

import React from 'react'; import { render, cleanup } from '@testing-library/react'; import TestElements from './TestElements' afterEach(cleanup); it('should equal to 0', () => { const { getByTestId } = render(); expect(getByTestId('counter')).toHaveTextContent(0) }); 

Nagu näete, on süntaks üsna sarnane eelmise testiga. Ainus erinevus on see, getByTestIdet valime vajalikud elemendid (pidage meeles data-testid) ja kontrollime, kas see on testi läbinud. Teiste sõnadega kontrollime, kas teksti sisu on olemas

{ counter }

on võrdne 0-ga.

Kontrollige, kas nupud on lubatud või keelatud:

TestElements.test.js (lisage faili järgmine koodiplokk)

 it('should be enabled', () => { const { getByTestId } = render(); expect(getByTestId('button-up')).not.toHaveAttribute('disabled') }); it('should be disabled', () => { const { getByTestId } = render(); expect(getByTestId('button-down')).toBeDisabled() }); 

Siin, nagu tavaliselt, getByTestIdvalime elemendid ja kontrollime esimese testi jaoks, kas nupul on disabledatribuut. Ja teiseks, kui nupp on keelatud või mitte.

Ja kui salvestate faili või käivitate oma terminalis uuesti yarn test, test läbib.

Palju õnne! Teie esimene test on läbitud!

palju õnne

Nüüd õpime järgmises jaotises sündmuse testimist.

3. Sündmuste testimine

Before writing our unit tests, let's first check what the TestEvents.js looks like.

  • TestEvents.js
import React from 'react' const TestEvents = () => { const [counter, setCounter] = React.useState(0) return (  

{ counter }

setCounter(counter + 1)}> Up setCounter(counter - 1)}>Down ) } export default TestEvents

Now, let's write the tests.

Test if the counter increments and decrements correctly when we click on buttons:

TestEvents.test.js

import React from 'react'; import { render, cleanup, fireEvent } from '@testing-library/react'; import TestEvents from './TestEvents' afterEach(cleanup); it('increments counter', () => { const { getByTestId } = render(); fireEvent.click(getByTestId('button-up')) expect(getByTestId('counter')).toHaveTextContent('1') }); it('decrements counter', () => { const { getByTestId } = render(); fireEvent.click(getByTestId('button-down')) expect(getByTestId('counter')).toHaveTextContent('-1') }); 

As you can see, these two tests are very similar except the expected text content.

The first test fires a click event with fireEvent.click() to check if the counter increments to 1 when the button is clicked.

And the second one checks if the counter decrements to -1 when the button is clicked.

fireEvent has several methods you can use to test events, so feel free to dive into the documentation to learn more.

Now that we know how to test events, let's move on and learn in the next section how to deal with asynchronous actions.

4. Testing asynchronous actions

An asynchronous action is something that can take time to complete. It can be an HTTP request, a timer, and so on.

Now, let's check the TestAsync.js file.

  • TestAsync.js
import React from 'react' const TestAsync = () => { const [counter, setCounter] = React.useState(0) const delayCount = () => ( setTimeout(() => { setCounter(counter + 1) }, 500) ) return (  

{ counter }

Up setCounter(counter - 1)}>Down ) } export default TestAsync

Here, we use setTimeout() to delay the incrementing event by 0.5s.

Test if the counter is incremented after 0.5s:

TestAsync.test.js

import React from 'react'; import { render, cleanup, fireEvent, waitForElement } from '@testing-library/react'; import TestAsync from './TestAsync' afterEach(cleanup); it('increments counter after 0.5s', async () => { const { getByTestId, getByText } = render(); fireEvent.click(getByTestId('button-up')) const counter = await waitForElement(() => getByText('1')) expect(counter).toHaveTextContent('1') }); 

To test the incrementing event, we first have to use async/await to handle the action because, as I said earlier, it takes time to complete.

Next, we use a new helper method getByText(). This is similar to getByTestId(), except that getByText() selects the text content instead of id or data-testid.

Now, after clicking to the button, we wait for the counter to be incremented with waitForElement(() => getByText('1')). And once the counter incremented to 1, we can now move to the condition and check if the counter is effectively equal to 1.

That being said, let's now move to more complex test cases.

Are you ready?

valmis

5. Testing React Redux

If you're new to React Redux, this article might help you. Otherwise, let's check what the TestRedux.js looks like.

  • TestRedux.js
import React from 'react' import { connect } from 'react-redux' const TestRedux = ({counter, dispatch}) => { const increment = () => dispatch({ type: 'INCREMENT' }) const decrement = () => dispatch({ type: 'DECREMENT' }) return (  

{ counter }

Up Down ) } export default connect(state => ({ counter: state.count }))(TestRedux)

And for the reducer:

  • store/reducer.js
export const initialState = { count: 0, } export function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return { count: state.count + 1, } case 'DECREMENT': return { count: state.count - 1, } default: return state } } 

As you can see, there is nothing fancy – it's just a basic Counter Component handled by React Redux.

Now, let's write the unit tests.

Test if the initial state is equal to 0:

TestRedux.test.js

import React from 'react' import { createStore } from 'redux' import { Provider } from 'react-redux' import { render, cleanup, fireEvent } from '@testing-library/react'; import { initialState, reducer } from '../store/reducer' import TestRedux from './TestRedux' const renderWithRedux = ( component, { initialState, store = createStore(reducer, initialState) } = {} ) => { return { ...render({component}), store, } } afterEach(cleanup); it('checks initial state is equal to 0', () => { const { getByTestId } = renderWithRedux() expect(getByTestId('counter')).toHaveTextContent('0') }) 

There are a couple of things we need to import to test React Redux. And here, we create our own helper function renderWithRedux() to render the component since it will be used several times.

renderWithRedux() receives as parameters the component to render, the initial state, and the store. If there is no store, it will create a new one, and if it doesn't receive an initial state or a store, it returns an empty object.

Next, we use render() to render the component and pass the store to the Provider.

That being said, we can now pass the component TestRedux to renderWithRedux() to test if the counter is equal to 0.

Test if the counter increments and decrements correctly:

TestRedux.test.js (add the following code block to the file)

it('increments the counter through redux', () => { const { getByTestId } = renderWithRedux(, {initialState: {count: 5} }) fireEvent.click(getByTestId('button-up')) expect(getByTestId('counter')).toHaveTextContent('6') }) it('decrements the counter through redux', () => { const { getByTestId} = renderWithRedux(, { initialState: { count: 100 }, }) fireEvent.click(getByTestId('button-down')) expect(getByTestId('counter')).toHaveTextContent('99') }) 

To test the incrementing and decrementing events, we pass an initial state as a second argument to renderWithRedux(). Now, we can click on the buttons and test if the expected result matches the condition or not.

Now, let's move to the next section and introduce React Context.

React Router and Axios will come next – are you still with me?

muidugi

6. Testing React Context

If you're new to React Context, check out this article first. Otherwise, let's check the TextContext.js file.

  • TextContext.js
import React from "react" export const CounterContext = React.createContext() const CounterProvider = () => { const [counter, setCounter] = React.useState(0) const increment = () => setCounter(counter + 1) const decrement = () => setCounter(counter - 1) return (    ) } export const Counter = () => { const { counter, increment, decrement } = React.useContext(CounterContext) return (  

{ counter }

Up Down ) } export default CounterProvider

Now, the counter state is managed through React Context. Let's write the unit test to check if it behaves as expected.

Test if the initial state is equal to 0:

TextContext.test.js

import React from 'react' import { render, cleanup, fireEvent } from '@testing-library/react' import CounterProvider, { CounterContext, Counter } from './TestContext' const renderWithContext = ( component) => { return { ...render(  {component} ) } } afterEach(cleanup); it('checks if initial state is equal to 0', () => { const { getByTestId } = renderWithContext() expect(getByTestId('counter')).toHaveTextContent('0') }) 

As in the previous section with React Redux, here we use the same approach, by creating a helper function renderWithContext() to render the component. But this time, it receives only the component as a parameter. And to create a new context, we pass CounterContext to the Provider.

Now, we can test if the counter is initially equal to 0 or not.

Test if the counter increments and decrements correctly:

TextContext.test.js (add the following code block to the file)

 it('increments the counter', () => { const { getByTestId } = renderWithContext() fireEvent.click(getByTestId('button-up')) expect(getByTestId('counter')).toHaveTextContent('1') }) it('decrements the counter', () => { const { getByTestId} = renderWithContext() fireEvent.click(getByTestId('button-down')) expect(getByTestId('counter')).toHaveTextContent('-1') }) 

As you can see, here we fire a click event to test if the counter increments correctly to 1 and decrements to -1.

That being said, we can now move to the next section and introduce React Router.

7. Testing React Router

If you want to dive into React Router, this article might help you. Otherwise, let's check the TestRouter.js file.

  • TestRouter.js
import React from 'react' import { Link, Route, Switch, useParams } from 'react-router-dom' const About = () =>

About page

const Home = () =>

Home page

const Contact = () => { const { name } = useParams() return

{name}

} const TestRouter = () => { const name = 'John Doe' return ( Home About Contact ) } export default TestRouter

Here, we have some components to render when navigating the Home page.

Now, let's write the tests:

  • TestRouter.test.js
import React from 'react' import { Router } from 'react-router-dom' import { render, fireEvent } from '@testing-library/react' import { createMemoryHistory } from 'history' import TestRouter from './TestRouter' const renderWithRouter = (component) => { const history = createMemoryHistory() return { ...render (  {component}  ) } } it('should render the home page', () => { const { container, getByTestId } = renderWithRouter() const navbar = getByTestId('navbar') const link = getByTestId('home-link') expect(container.innerHTML).toMatch('Home page') expect(navbar).toContainElement(link) }) 

To test React Router, we have to first have a navigation history to start with. Therefore we use createMemoryHistory() to well as the name guessed to create a navigation history.

Next, we use our helper function renderWithRouter() to render the component and pass history to the Router component. With that, we can now test if the page loaded at the start is the Home page or not. And if the navigation bar is loaded with the expected links.

Test if it navigates to other pages with the parameters when we click on links:

TestRouter.test.js (add the following code block to the file)

it('should navigate to the about page', ()=> { const { container, getByTestId } = renderWithRouter() fireEvent.click(getByTestId('about-link')) expect(container.innerHTML).toMatch('About page') }) it('should navigate to the contact page with the params', ()=> { const { container, getByTestId } = renderWithRouter() fireEvent.click(getByTestId('contact-link')) expect(container.innerHTML).toMatch('John Doe') }) 

Now, to check if the navigation works, we have to fire a click event on the navigation links.

For the first test, we check if the content is equal to the text in the About Page, and for the second, we test the routing params and check if it passed correctly.

We can now move to the final section and learn how to test an Axios request.

We're almost done!

ikka veel siin

8. Testing HTTP Request

As usual, let's first see what the TextAxios.js file looks like.

  • TextAxios.js
import React from 'react' import axios from 'axios' const TestAxios = ({ url }) => { const [data, setData] = React.useState() const fetchData = async () => { const response = await axios.get(url) setData(response.data.greeting) } return (  Load Data { data ? {data} : 

Loading...

} ) } export default TestAxios

As you can see here, we have a simple component that has a button to make a request. And if the data is not available, it will display a loading message.

Now, let's write the tests.

Test if the data are fetched and displayed correctly:

TextAxios.test.js

import React from 'react' import { render, waitForElement, fireEvent } from '@testing-library/react' import axiosMock from 'axios' import TestAxios from './TestAxios' jest.mock('axios') it('should display a loading text', () => { const { getByTestId } = render() expect(getByTestId('loading')).toHaveTextContent('Loading...') }) it('should load and display the data', async () => { const url = '/greeting' const { getByTestId } = render() axiosMock.get.mockResolvedValueOnce({ data: { greeting: 'hello there' }, }) fireEvent.click(getByTestId('fetch-data')) const greetingData = await waitForElement(() => getByTestId('show-data')) expect(axiosMock.get).toHaveBeenCalledTimes(1) expect(axiosMock.get).toHaveBeenCalledWith(url) expect(greetingData).toHaveTextContent('hello there') }) 

This test case is a bit different because we have to deal with an HTTP request. And to do that, we have to mock an axios request with the help of jest.mock('axios').

Now, we can use axiosMock and apply a get() method to it. Finally we will use the Jest function mockResolvedValueOnce() to pass the mocked data as a parameter.

With that, now for the second test we can click to the button to fetch the data and use async/await to resolve it. And now we have to test 3 things:

  1. If the HTTP request has been done correctly
  2. If the HTTP request has been done with the url
  3. If the data fetched matches the expectation.

And for the first test, we just check if the loading message is displayed when we have no data to show.

That being said, we're now done with the 8 simple steps to start testing your React Apps.

Don't be scared to test anymore.

ei karda

Final Thoughts

React Testing Library on suurepärane pakett React Apps'i testimiseks. See annab meile juurdepääsu jest-domsobijatele, keda saame kasutada oma komponentide tõhusamaks ja heade tavade testimiseks. Loodetavasti oli see artikkel kasulik ja see aitab teil tulevikus luua tugevaid rakendusi React.

Lõppenud projekti leiate siit

Täname, et lugesite seda!

Loe rohkem artikleid - Telli minu uudiskiri - Jälgi mind twitteris

Muid selliseid artikleid saate lugeda minu ajaveebist.

Järgmised sammud

Reageeri testimise raamatukogu dokumendid

React Testing Library Cheatsheet

Jest DOM-i sobitajate petukiri

Jest Docs