ReactJS - 测试
测试是确保任何应用程序中创建的功能符合业务逻辑和编码规范的过程之一。React 建议使用 React 测试库 来测试 React 组件,并使用 jest 测试运行器来运行测试。react-testing-library 允许单独检查组件。
可以使用以下命令将其安装在应用程序中 −
npm install --save @testing-library/react @testing-library/jest-dom
创建 React 应用
创建 React 应用 默认配置 React 测试库 和 jest 测试运行器。因此,测试使用 Create React App 创建的 React 应用程序只需一个命令即可。
cd /go/to/react/application npm test
npm test 命令类似于 npm build 命令。当开发人员更改代码时,两者都会重新编译。在命令提示符中执行命令后,它会发出以下问题。
No tests found related to files changed since last commit. Press `a` to run all tests, or run Jest with `--watchAll`. Watch Usage › Press a to run all tests. › Press f to run only failed tests. › Press q to quit watch mode. › Press p to filter by a filename regex pattern. › Press t to filter by a test name regex pattern. › Press Enter to trigger a test run.
按 a 将尝试运行所有测试脚本并最终总结结果,如下所示 −
Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 4.312 s, estimated 12 s Ran all test suites. Watch Usage: Press w to show more.
在自定义应用程序中进行测试
在本章中,我们使用 Rollup 捆绑器 编写自定义 React 应用程序,并使用 React 测试库 和 jest 测试运行器对其进行测试。
首先,按照创建 React 应用程序 一章中的说明,使用 Rollup 捆绑器创建一个新的 React 应用程序 react-test-app。
接下来,安装测试库。
cd /go/to/react-test-app npm install --save @testing-library/react @testing-library/jest-dom
接下来,在您最喜欢的编辑器中打开该应用程序。
接下来,在 下创建一个文件 HelloWorld.test.js src/components 文件夹,为 HelloWorld 组件编写测试并开始编辑。
接下来,导入 react 库。
import React from 'react';
接下来,导入测试库。
import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom';
接下来,导入我们的 HelloWorld 组件。
import HelloWorld from './HelloWorld';
接下来,编写测试来检查文档中是否存在 Hello World 文本。
test('test scenario 1', () => { render(<HelloWorld />); const element = screen.getByText(/Hello World/i); expect(element).toBeInTheDocument(); });
下面给出测试代码的完整源代码 −
import React from 'react'; import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom'; import HelloWorld from './HelloWorld'; test('test scenario 1', () => { render(<HelloWorld />); const element = screen.getByText(/Hello World/i); expect(element).toBeInTheDocument(); });
接下来,如果系统中尚未安装 jest 测试运行器,请安装它。
npm install jest -g
接下来,在应用程序的根文件夹中运行 jest 命令。
jest
接下来,在应用程序的根文件夹中运行 jest 命令。
PASS src/components/HelloWorld.test.js √ test scenario 1 (29 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 5.148 s Ran all test suites.