使用 React Testing Library 辅助 Jest 进行单测

因为与常规的接口逻辑测试不同,前端的单元测试涉及到 Dom 和事件的模拟,我们还需要选用一个辅助库来协助我们模拟相关的场景。

有两个主流的辅助库选择,Enzyme 和 React Testing Library,这两个库都是非常优秀的辅助库,它们都提供了测试应用程序所需的所有工具,都能够满足我们的单测需求,但从配置以及测试思路的角度上看,我更推荐大家使用 React Testing Library,下面我们将具体说明。

React Testing Library 配置

在使用 React Testing Library 之前还需要安装依赖

  • @testing-library/jest-dom:用于 dom、样式类型等元素选取。
  • @testing-library/react:提供针对 React 的单测渲染能力。
  • @testing-library/user-event:用于单测场景下事件的模拟。
1
npm install @testing-library/jest-dom @testing-library/react @testing-library/user-event --save-dev

为了让 expect 可以适配 React testing library 提供的相关断言,我们可以在根目录创建一个 jest-dom-setup.js 文件,用于全局导入 @testing-library/jest-dom 。

1
2
//  jest_dom_setup.js
import '@testing-library/jest-dom'

将这个文件配置到 jest.config.ts 的 setupFilesAfterEnv 属性中。这样 Jest 在运行前会运行 @testing-library/jest-dom ,这样我们就不用每次都单独导入一次 @testing-library/jest-dom 了。

1
setupFilesAfterEnv: ["<rootDir>/jest-dom-setup.js"],

这样 React Testing Library 就能在你的项目正常运行了。如果我们使用的是 create-react-app 脚手架创建的项目就不需要配置这些,因为 create-react-app 会帮我们配置好。