如何在基于TS的CRA项目中通过Cypress组件测试生成覆盖率报告
在TypeScript CRA项目中用Cypress组件测试生成LCOV覆盖率报告
1. 安装依赖
执行以下命令安装所需工具包:
npm install -D cypress @cypress/react @cypress/webpack-dev-server @cypress/code-coverage babel-plugin-istanbul
2. 初始化Cypress组件测试
运行初始化命令生成Cypress组件测试的基础配置文件:
npx cypress open --component
按照向导完成初始化,会自动创建cypress目录及相关配置文件。
3. 配置代码插装
3.1 配置Babel插装
在项目根目录的package.json中添加Babel配置,引入istanbul插件实现代码插装:
"babel": { "presets": ["react-app"], "plugins": [ ["istanbul", { "include": "src/**/*", "exclude": ["src/**/*.test.tsx", "src/**/*.spec.tsx"] }] ] }
如果项目使用单独的babel.config.js,则修改为:
module.exports = { presets: ['react-app'], plugins: [ ["istanbul", { "include": "src/**/*", "exclude": ["src/**/*.test.tsx", "src/**/*.spec.tsx"] }] ] };
3.2 配置Cypress支持覆盖率
在cypress/support/component.ts中导入覆盖率支持脚本:
import '@cypress/code-coverage/support'
3.3 配置Cypress Node事件
修改cypress.config.ts,添加覆盖率任务并配置Dev Server:
import { defineConfig } from 'cypress' import codeCoverageTask from '@cypress/code-coverage/task' export default defineConfig({ component: { devServer: { framework: 'create-react-app', bundler: 'webpack' }, setupNodeEvents(on, config) { // 注册覆盖率收集任务 codeCoverageTask(on, config) return config } } })
4. 运行测试并生成LCOV报告
执行无头模式的组件测试:
npx cypress run --component
测试完成后,项目根目录会生成coverage文件夹,其中的lcov.info就是所需的LCOV格式覆盖率报告,同时还会生成HTML格式的可视化报告。
常见问题排查
- 如果覆盖率统计包含测试文件:检查Babel配置中的
exclude规则,确保排除所有测试文件(.test.tsx/.spec.tsx)。 - Jenkins环境下无覆盖率报告:确保Jenkins构建时执行测试命令的环境变量
NODE_ENV为test,且依赖安装完整。
内容的提问来源于stack exchange,提问作者Sophie McCarrell
相关产品推荐
相关产品推荐

