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

如何在Cypress 9.7.0中仅运行E2E集成测试(排除组件测试文件)

解决Cypress 9.7.0中E2E测试误执行组件测试文件的问题

首先得说明,你遇到的问题核心在于Cypress 9.7.0的配置结构不支持E2E测试用嵌套的integration字段——组件测试的component嵌套配置是官方明确支持的,但E2E的相关配置项必须直接放在顶层,你之前添加的integration嵌套对象会被Cypress直接忽略,所以E2E模式下还是沿用了默认的测试文件匹配规则,导致把.test.ct.ts文件也一起执行了。

下面给你几个可行的解决思路,按推荐程度排序:

方案1:通过Plugins文件动态配置测试规则(最推荐)

这个方案不用拆分配置文件,也不用每次加命令行参数,让Cypress自动根据测试类型匹配对应文件:

在你的test/cypress/plugins/index.ts文件中,修改导出的配置函数,根据当前测试类型动态设置testFiles:

module.exports = (on, config) => {
  // 判断当前运行的是组件测试还是E2E测试
  const isComponentMode = config.testingType === 'component';

  if (isComponentMode) {
    // 组件测试只匹配ct后缀的文件
    config.testFiles = ['**/*.test.ct.ts', '**/*.test.ct.js'];
  } else {
    // E2E测试只匹配e2e后缀的文件
    config.testFiles = ['**/*.test.e2e.ts', '**/*.test.e2e.js'];
  }

  return config;
};

修改后,不管你运行cypress run(E2E模式)还是cypress run --component(组件测试模式),Cypress都会自动加载对应的文件规则,不会互相干扰。

方案2:拆分配置文件

给E2E和组件测试分别创建独立的配置文件,运行时指定对应的配置:

  1. 创建test/cypress/cypress.e2e.json(E2E专用配置):
{
  "baseUrl": "http://localhost:8080/",
  "fixturesFolder": "test/cypress/fixtures",
  "integrationFolder": "test/cypress/tests/",
  "testFiles": ["**/*.test.e2e.ts","**/*.test.e2e.js"],
  "pluginsFile": "test/cypress/plugins/index.ts",
  "screenshotsFolder": "test/cypress/screenshots",
  "supportFile": "test/cypress/support/index.ts",
  "videosFolder": "test/cypress/videos",
  "video": false
}
  1. 保留原有的cypress.json作为组件测试的配置(或者也可以单独创建cypress.ct.json)。

  2. 在package.json的scripts中添加对应的运行命令:

{
  "scripts": {
    "cy:e2e": "cypress run --config-file test/cypress/cypress.e2e.json",
    "cy:component": "cypress run --component --config-file test/cypress/cypress.json"
  }
}

之后运行npm run cy:e2e就只会执行E2E测试文件,运行npm run cy:component执行组件测试文件。

方案3:运行命令时直接指定测试文件规则

不用修改配置文件,每次运行测试时通过命令行参数覆盖testFiles:

  • 运行E2E测试(命令行模式):
cypress run --testFiles "**/*.test.e2e.js,**/*.test.e2e.ts"
  • 打开Cypress GUI并只加载E2E文件:
cypress open --testFiles "**/*.test.e2e.js,**/*.test.e2e.ts"

组件测试因为你已经在cypress.json的component字段里配置了testFiles,所以直接运行cypress run --component或者cypress open --component就可以正常只加载组件测试文件。

内容的提问来源于stack exchange,提问作者c.m.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:52:46