You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无react-scripts时,如何在start命令中添加-r @cypress/instrument-cra实现代码覆盖率?

解决方法

1. 修改启动命令

直接在node命令后添加-r参数预加载@cypress/instrument-cra,修改后的启动命令如下:

"start": "node -r @cypress/instrument-cra index.js"

-r(即--require)是Node.js的内置选项,作用是在执行目标脚本前预加载指定模块,正好满足你的需求。

2. 适配非Create React App项目的代码覆盖配置

因为你没有使用react-scripts,@cypress/instrument-cra针对CRA的封装逻辑无法直接复用,需要手动补充代码覆盖的核心配置:

  • 安装依赖:
    执行以下命令安装代码覆盖所需的工具包:

    npm install -D @cypress/instrument-cra nyc cypress-code-coverage babel-plugin-istanbul
    
  • 配置Babel插桩:
    在你的Babel配置文件(.babelrc或babel.config.js)中,添加babel-plugin-istanbul插件,仅在测试环境启用插桩(避免影响生产代码):

    {
      "env": {
        "test": {
          "plugins": ["istanbul"]
        }
      }
    }
    
  • 配置Cypress插件:
    在cypress.config.js中注册代码覆盖任务:

    const { defineConfig } = require('cypress')
    
    module.exports = defineConfig({
      e2e: {
        setupNodeEvents(on, config) {
          require('cypress-code-coverage/task')(on, config)
          return config
        },
      },
    })
    
  • 加载Cypress支持文件:
    在cypress/support/e2e.js(或index.js)中导入代码覆盖支持模块:

    import 'cypress-code-coverage/support'
    

3. 验证配置

启动项目和Cypress后,运行测试用例,测试完成后在项目根目录执行npx nyc report即可生成代码覆盖报告。

内容的提问来源于stack exchange,提问作者Neha Chaudhary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 22:40:33