单元测试设置
¥Unit Testing Setup
Ionic 需要一些额外的步骤来设置单元测试。如果你使用的是 Ionic 入门项目,这些步骤已经为你完成。
¥Ionic requires a few additional steps to set up unit tests. If you are using an Ionic starter project, these steps have already been completed for you.
安装 React 测试库
¥Install React Testing Library
React 测试库是一组实用程序,可以更轻松地测试 React 组件。它用于与组件交互并测试它们的行为。
¥React Testing Library is a set of utilities that make it easier to test React components. It's used to interact with components and test their behavior.
npm install --save-dev @testing-library/react @testing-library/jest-dom @testing-library/user-event
初始化 Ionic React
¥Initialize Ionic React
Ionic React 要求在运行任何测试之前调用 setupIonicReact
函数。如果不这样做,将导致基于模式的类和平台行为无法应用于你的组件。
¥Ionic React requires the setupIonicReact
function to be called before any tests are run. Failing to do so will result in mode-based classes and platform behaviors not being applied to your components.
在 src/setupTest.ts
中添加以下代码:
¥In src/setupTest.ts
, add the following code:
import '@testing-library/jest-dom/extend-expect';
+ import { setupIonicReact } from '@ionic/react';
+ setupIonicReact();
// Mock matchmedia
window.matchMedia = window.matchMedia || function () {
return {
matches: false,
addListener: function () { },
removeListener: function () { }
};
};