最近项目上对UT coverage有要求。有同事推荐使用Cypress,因为它是运行在真实的浏览器环境中。而react testing library是基于jsdom,再加上因为我们项目中的组件库是基于web component的,所以会有很多shadow DOM的问题。
Cypress不仅可以做end-to-end test,还可以做unit test。我目前理解它的unit test是Component Test。接下来的步骤是在CRA的基础上setup Cypress的component test。
-
创建一个CRA的项目
yarn create react-app react-cypress-demo
-
添加cypress相关依赖
yarn add cypress @cypress/react @cypress/webpack-dev-server --dev
-
到目前为止,可以运行以下命令来生成cypress的configuration文件
yarn cypress open-ct
命令执行完后,在根目录会生成一个cypress.json
文件和一个cypress
的文件夹。 -
在
cypress.json
中添加如下配置,其中testFiles
根据实际项目约定来定义即可。{ "component": { "testFiles": "**/*.test.{js,ts,jsx,tsx}", "componentFolder": "src" } }
-
在
cypress/plugins/index.js
中添加如下配置。const injectDevServer = require("@cypress/react/plugins/react-scripts") module.exports = (on, config) => { injectDevServer(on, config) return config }
以上就配置好了cypress环境。
接下来可以基于App.js的现有内容将App.test.js用cypress改写如下。
import { mount } from '@cypress/react';
import App from './App';
it('renders learn react link', () => {
mount(<App />);
cy.get('a').contains('Learn React');
});
这时就可以运行yarn cypress open-ct
来看UT的执行结果了,它会启动一个新的窗口,需要点击左边的spec,UT才会运行。
References:
Getting Started with Cypress Component Testing (React)
Component Test Introduction
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步