测试是确保在任何应用程序中创建的功能都按照业务逻辑和编码规范工作的过程之一。React 推荐使用 React 测试库来测试 React 组件,并使用 jest 测试运行器来运行测试。react-testing-library 允许单独检查组件。
可以使用以下命令将其安装在应用程序中 -
创建 React 应用
创建 React 应用默认配置 React 测试库和 jest 测试运行器。因此,测试使用 Create React App 创建的 React 应用程序只是一个命令。
npm test
npm test 命令类似于 npm build 命令。两者都会在开发人员更改代码时重新编译。在命令提示符中执行命令后,它会发出以下问题。
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 将尝试运行所有测试脚本,最后总结结果,如下所示 -
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。
接下来,安装测试库。
npm install --save @testing-library/react @testing-library/jest-dom
接下来,在您最喜欢的编辑器中打开应用程序。
接下来,创建一个文件,HelloWorld.test.js src/components 文件夹下,为 HelloWorld 组件编写测试并开始编辑。
接下来,导入 react 库。
接下来,导入测试库。
import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom';
接下来,导入我们的 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 test runner,如果它尚未在系统中安装。
接下来,在应用程序的根文件夹中运行 jest 命令。
接下来,在应用程序的根文件夹中运行 jest 命令。
√ 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.