react测试组件_测试React组件

react测试组件

The easiest way to start with testing React components is doing snapshot testing, a testing technique that lets you test components in isolation.

开始测试React组件的最简单方法是进行快照测试,这是一种测试技术,可让您隔离测试组件。

If you are familiar with testing software, it’s just like unit testing you do for classes: you test each component functionality.

如果您熟悉测试软件,就像您对类进行单元测试一样:您测试每个组件的功能。

I assume you created a React app with create-react-app, which already comes with Jest installed, the testing package we’ll need.

我假设您使用create-react-app创建了一个React应用,该create-react-app已经安装了Jest ,这是我们需要的测试包。

Let’s start with a simple test. CodeSandbox is a great environment to try this out. Start with a React sandbox, and create an App.js component in a components folder, and add an App.test.js file.

让我们从一个简单的测试开始。 CodeSandbox是一个很好的尝试环境。 从React沙箱开始,在components文件夹中创建一个App.js组件,然后添加一个App.test.js文件。

import React from 'react'

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  )
}

Our first test is dumb:

我们的第一个测试是愚蠢的:

test('First test', () => {
  expect(true).toBeTruthy()
})

When CodeSandbox detects test files, it automatically runs them for you, and you can click the Tests button in the bottom of the view to show your test results:

当CodeSandbox检测到测试文件时,它将自动为您运行它们,您可以单击视图底部的“测试”按钮以显示测试结果:

A test file can contain multiple tests:

一个测试文件可以包含多个测试:

Let’s do something a bit more useful now, to actually test a React component. We only have App now, which is not doing anything really useful, so let’s first set up the environment with a little application with more functionality: the counter app we built previously. If you skipped it, you can go back and read how we built it, but for easier reference I add it here again.

现在让我们做一些更有用的操作,以实际测试React组件。 现在我们只有App,它并没有做任何真正有用的事情,因此让我们首先使用一个具有更多功能的小应用程序来设置环境:我们之前构建的计数器应用程序。 如果您跳过它,则可以返回并阅读我们如何构建它,但是为了便于参考,我再次在此处添加它。

It’s just 2 components: App and Button. Create the App.js file:

它只有2个组件:App和Button。 创建App.js文件:

import React, { useState } from 'react'
import Button from './Button'

const App = () => {
  const [count, setCount] = useState(0)

  const incrementCount = increment => {
    setCount(count + increment)
  }

  return (
    <div>
      <Button increment={1} onClickFunction={incrementCount} />
      <Button increment={10} onClickFunction={incrementCount} />
      <Button increment={100} onClickFunction={incrementCount} />
      <Button increment={1000} onClickFunction={incrementCount} />
      <span>{count}</span>
    </div>
  )
}

export default App

and the Button.js file:

Button.js文件:

import React from 'react'

const Button = ({ increment, onClickFunction }) => {
  const handleClick = () => {
    onClickFunction(increment)
  }
  return <button onClick={handleClick}>+{increment}</button>
}

export default Button

We are going to use the react-testing-library, which is a great help as it allows us to inspect the output of every component and to apply events on them. You can read more about it on https://github.com/kentcdodds/react-testing-library or by watching this video.

我们将使用react-testing-library ,这是一个很大的帮助,因为它允许我们检查每个组件的输出并将事件应用于它们。 您可以在https://github.com/kentcdodds/react-testing-library或观看此视频中了解更多信息。

Let’s test the Button component first.

让我们首先测试Button组件。

We start by importing render and fireEvent from react-testing-library, two helpers. The first lets us render JSX. The second lets us emit events on a component.

我们从两个帮助程序react-testing-library导入renderfireEvent开始。 第一个让我们渲染JSX。 第二个让我们在组件上发出事件。

Create a Button.test.js and put it in the same folder as Button.js.

创建一个Button.test.js并将其放在与Button.js相同的文件夹中。

import React from 'react'
import { render, fireEvent } from 'react-testing-library'
import Button from './Button'

Buttons are used in the app to accept a click event and then they call a function passed to the onClickFunction prop. We add a count variable and we create a function that increments it:

应用程序中使用按钮来接受click事件,然后它们调用传递给onClickFunction的函数。 我们添加一个count变量,并创建一个递增它的函数:

let count

const incrementCount = increment => {
  count += increment
}

Now off to the actual tests. We first initialize count to 0, and we render a +1 Button component passing a 1 to increment and our incrementCount function to onClickFunction.

现在开始实际测试。 我们首先初始化计数为0,我们呈现一个+1 Button组件传递一个1increment和我们incrementCount功能onClickFunction

Then we get the content of the first child of the component, and we check it outputs +1.

然后,我们获得组件第一个子代的内容,并检查其输出+1

We then proceed to clicking the button, and we check that the count got from 0 to 1:

然后,我们继续单击按钮,并检查计数是否从0变为1:

test('+1 Button works', () => {
  count = 0
  const { container } = render(
    <Button increment={1} onClickFunction={incrementCount} />
  )
  const button = container.firstChild
  expect(button.textContent).toBe('+1')
  expect(count).toBe(0)
  fireEvent.click(button)
  expect(count).toBe(1)
})

Similarly we test a +100 button, this time checking the output is +100 and the button click increments the count of 100.

同样,我们测试了一个+100按钮,这次检查输出为+100并且单击按钮将计数增加100。

test('+100 Button works', () => {
  count = 0
  const { container } = render(
    <Button increment={100} onClickFunction={incrementCount} />
  )
  const button = container.firstChild
  expect(button.textContent).toBe('+100')
  expect(count).toBe(0)
  fireEvent.click(button)
  expect(count).toBe(100)
})

Let’s test the App component now. It shows 4 buttons and the result in the page. We can inspect each button and see if the result increases when we click them, clicking multiple times as well:

现在让我们测试App组件。 它在页面中显示4个按钮和结果。 我们可以检查每个按钮,并在单击它们时也多次单击以查看结果是否增加:

import React from 'react'
import { render, fireEvent } from 'react-testing-library'
import App from './App'

test('App works', () => {
  const { container } = render(<App />)
  console.log(container)
  const buttons = container.querySelectorAll('button')

  expect(buttons[0].textContent).toBe('+1')
  expect(buttons[1].textContent).toBe('+10')
  expect(buttons[2].textContent).toBe('+100')
  expect(buttons[3].textContent).toBe('+1000')

  const result = container.querySelector('span')
  expect(result.textContent).toBe('0')
  fireEvent.click(buttons[0])
  expect(result.textContent).toBe('1')
  fireEvent.click(buttons[1])
  expect(result.textContent).toBe('11')
  fireEvent.click(buttons[2])
  expect(result.textContent).toBe('111')
  fireEvent.click(buttons[3])
  expect(result.textContent).toBe('1111')
  fireEvent.click(buttons[2])
  expect(result.textContent).toBe('1211')
  fireEvent.click(buttons[1])
  expect(result.textContent).toBe('1221')
  fireEvent.click(buttons[0])
  expect(result.textContent).toBe('1222')
})

Check the code working on this CodeSandbox: https://codesandbox.io/s/pprl4y0wq

检查在此CodeSandbox上运行的代码: https ://codesandbox.io/s/pprl4y0wq

翻译自: https://flaviocopes.com/react-testing-components/

react测试组件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值