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

如何为create-next-app创建的React/Next.js/TypeScript项目添加Cypress代码覆盖率

解决方案:Next.js 13.4.7 + TypeScript + Cypress + SWC 代码覆盖率配置

一、确认基础项目配置

确保你的项目是通过create-next-app@13.4.7创建的默认配置:

  • 包含TypeScript、ESLint、Tailwind CSS、src/目录、App Router
  • 无自定义Babel配置(避免和SWC冲突引发编译错误)

二、基础Cypress配置

如果还没完成Cypress的基础安装,执行以下命令:

npm install cypress --save-dev

在package.json中添加测试脚本:

{
  "scripts": {
    "cypress:open": "cypress open",
    "cypress:run": "cypress run",
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  }
}

三、SWC代码覆盖率核心配置

之前使用swc-plugin-coverage-instrument未生成__coverage__,是因为缺少Next.js的SWC插件配置和Cypress的覆盖率收集逻辑,按以下步骤操作:

1. 安装依赖包

npm install @swc/jest swc-plugin-coverage-instrument @cypress/code-coverage --save-dev

2. 配置Next.js的SWC插件

在项目根目录创建/修改next.config.js,添加SWC覆盖率插件配置:

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    swcPlugins: [
      ['swc-plugin-coverage-instrument', {
        cwd: process.cwd(),
        exclude: ['node_modules', 'cypress', '.next'],
        include: ['src/**/*.{ts,tsx}']
      }]
    ]
  }
}

module.exports = nextConfig

3. 配置Cypress收集覆盖率数据

修改cypress.config.ts,添加覆盖率任务支持:

import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      require('@cypress/code-coverage/task')(on, config)
      return config
    },
    baseUrl: 'http://localhost:3000',
  },
  component: {
    devServer: {
      framework: 'next',
      bundler: 'webpack',
    },
    setupNodeEvents(on, config) {
      require('@cypress/code-coverage/task')(on, config)
      return config
    },
  },
})

然后在cypress/support/e2e.ts和cypress/support/component.ts中导入覆盖率支持脚本:

import '@cypress/code-coverage/support'

4. 调整测试运行命令

在package.json中添加整合开发服务与测试的脚本:

{
  "scripts": {
    "test:e2e": "npm run dev & cypress run",
    "test:component": "cypress run --component"
  }
}

Windows系统请替换为:"test:e2e": "start npm run dev && cypress run"

四、验证覆盖率是否生效

  1. 启动开发服务器:npm run dev
  2. 打开Cypress并执行测试:npm run cypress:open
  3. 测试完成后,项目根目录会生成coverage文件夹,打开coverage/lcov-report/index.html即可查看详细的覆盖率报告

五、常见问题排查

  • 仍无__coverage__生成:
    • 检查next.config.js中swcPlugins的include路径是否匹配你的源码文件
    • 删除项目中所有自定义Babel配置文件(如.babelrc、babel.config.js),避免强制Next.js切换到Babel
    • 清除.next缓存:rm -rf .next,然后重启开发服务器
  • 出现next/font相关编译错误:确保无自定义Babel配置,Next.js默认会使用SWC,不会触发该冲突

内容的提问来源于stack exchange,提问作者Hamid Mayeli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:35:14