Cypress 10+结合Cucumber+Typescript:如何通过标签运行测试(非跳过方式)
基于Cypress 10+ + Cucumber + TypeScript的标签测试运行方案
方法1:用Cucumber原生标签过滤(推荐)
Cucumber本身支持标签筛选测试,无需额外插件,直接通过命令行或配置文件即可实现,不会跳过测试,只会运行匹配标签的用例。
步骤1:给Feature文件添加标签
在你的.feature文件中按如下格式标记测试用例:
@smoke @login Feature: 用户登录功能 Scenario: 正确账号密码登录 Given 打开登录页面 When 输入正确的用户名和密码 Then 成功跳转到首页 @regression @profile Scenario: 查看用户个人信息 Given 已登录系统 When 点击个人信息入口 Then 显示正确的用户信息
步骤2:命令行指定标签运行测试
直接在启动命令中通过--env tags参数筛选:
- 运行单个标签的用例:
npx cypress run --env tags="@smoke"
- 运行满足任意一个标签的用例:
npx cypress run --env tags="@smoke or @regression"
- 运行同时包含多个标签的用例:
npx cypress run --env tags="@smoke and @login"
- 排除指定标签的用例:
npx cypress run --env tags="not @skip"
步骤3:配置文件默认设置标签(可选)
如果需要默认运行特定标签的测试,可在cypress.config.ts中配置:
import { defineConfig } from 'cypress'; import createBundler from '@bahmutov/cypress-esbuild-preprocessor'; import { addCucumberPreprocessorPlugin } from '@badeball/cypress-cucumber-preprocessor'; import createEsbuildPlugin from '@badeball/cypress-cucumber-preprocessor/esbuild'; export default defineConfig({ e2e: { async setupNodeEvents(on, config) { const bundler = createBundler({ plugins: [createEsbuildPlugin(config)], }); on('file:preprocessor', bundler); await addCucumberPreprocessorPlugin(on, config); // 设置默认标签,可被命令行参数覆盖 config.env.tags = '@smoke'; return config; }, specPattern: 'cypress/e2e/**/*.feature', }, });
方法2:借助@badeball/cypress-cucumber-preprocessor实现
Cypress 10+适配的官方Cucumber插件@badeball/cypress-cucumber-preprocessor原生支持标签过滤,替代无效的cypress-tag即可。
先确保依赖安装正确:
npm install @badeball/cypress-cucumber-preprocessor @bahmutov/cypress-esbuild-preprocessor esbuild --save-dev
之后按照方法1的配置和命令运行即可,插件会自动识别并过滤标签匹配的用例。
常见问题排查
cypress-tag无效是因为Cypress 10+架构变动,旧插件不兼容,替换为@badeball/cypress-cucumber-preprocessor即可解决。- 确保标签格式正确,必须以
@开头,标签名无空格。 - Windows环境下命令行的标签参数需用双引号包裹,比如
npx cypress run --env tags="@smoke"。
内容的提问来源于stack exchange,提问作者Suchit Narayan
相关产品推荐
相关产品推荐

