CucumberJs与Cypress如何隔离上下文支持相同描述的不同步骤实现
Cucumber 运行时默认会把所有步骤定义注册到全局上下文,相同匹配规则的步骤会优先匹配先加载的定义,因此会出现同名步骤被覆盖的问题,可通过以下几种方式实现步骤隔离:
方案1:启用按feature绑定步骤的规则(最适配当前场景,无需修改现有代码)
直接修改 cypress.config.ts 中的 cypress-cucumber-preprocessor 配置,开启同名文件自动绑定规则即可,示例配置如下:
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: { specPattern: '**/*.feature', async setupNodeEvents(on, config) { await addCucumberPreprocessorPlugin(on, config) on( 'file:preprocessor', createBundler({ plugins: [createEsbuildPlugin(config)], }) ) return config }, // 核心配置:[name] 会自动替换为feature文件的文件名,只加载对应同名步骤文件 stepDefinitions: 'cypress/e2e/steps/[name].spec.ts' }, })
配置完成后,bus.feature 只会加载同文件名的 bus.spec.ts 步骤定义,car.feature 只会加载 car.spec.ts,不会出现步骤冲突问题。
方案2:用标签隔离步骤作用域
如果不想修改全局配置,可以给不同业务的feature场景加上专属标签,再调整步骤定义的匹配规则:
- 在
bus.feature所有场景前加上@bus标签,car.feature所有场景前加上@car标签 - 修改两个步骤定义的匹配串,加上标签前缀:
// bus.spec.ts 中 Then('@bus I {string} the Destination page', (operation: operation) => { // 原有逻辑不变 }) // car.spec.ts 中 Then('@car I {string} the Destination page', (operation: operation) => { // 原有逻辑不变 })
方案3:参数化差异逻辑,复用同一步骤定义
从代码复用的角度出发,可以把业务模块作为参数传入步骤,不需要写两份重复定义:
// 统一放在公共步骤文件中 Then('I {string} the {string} module Destination page', (operation: operation, module: 'bus' | 'car') => { cy.location().should(location => { switch (operation) { case 'visit': expect(location.pathname).to.eq('/e2e/destination') break case `can't visit`: expect(location.pathname).to.eq(`/e2e/${module}`) break } }) })
后续在feature文件中调用时,直接传入对应的模块名即可:
Then I "can't visit" the "bus" module Destination page
内容的提问来源于stack exchange,提问作者axel
相关产品推荐
相关产品推荐

