cypress-cucumber不同step definition间传递提取价格的最佳实践
Cypress Cucumber跨步骤传递变量的最佳实现方案
共有三种常用实现方式,优先推荐Cypress别名方案:
方案1:使用Cypress Alias(官方推荐最佳实践)
Cypress提供的别名机制天生适合跨步骤传递数据,不会产生全局变量污染,且生命周期和当前测试场景绑定,场景执行结束后自动销毁,无需手动重置。
代码改造示例:
// 首页提取价格步骤 When('I go to home page I extract the price', () => { // 原有业务逻辑 const homePagePrice = 100 // 用wrap包装值后设置别名 cy.wrap(homePagePrice).as('homePagePrice') }) // 购物车页提取价格步骤 When('I go to shopping cart page I extract the price', () => { // 原有业务逻辑 const shoppingCartPagePrice = 100 cy.wrap(shoppingCartPagePrice).as('cartPagePrice') }) // 校验步骤 Then('the price on the home page and shopping cart page is same', () => { // 批量获取别名对应的值做对比 cy.get('@homePagePrice').then(homePrice => { cy.get('@cartPagePrice').then(cartPrice => { expect(homePrice).to.equal(cartPrice) }) }) })
方案2:使用Mocha上下文this
利用Cypress底层依赖的Mocha测试框架的上下文对象传递值,需要注意不能使用箭头函数定义步骤,箭头函数会绑定外部this导致无法访问Mocha上下文。
代码改造示例:
// 首页提取价格步骤,替换箭头函数为普通function When('I go to home page I extract the price', function() { // 原有业务逻辑 const homePagePrice = 100 // 挂载到this上下文 this.homePagePrice = homePagePrice }) // 购物车页提取价格步骤 When('I go to shopping cart page I extract the price', function() { // 原有业务逻辑 const shoppingCartPagePrice = 100 this.cartPagePrice = shoppingCartPagePrice }) // 校验步骤 Then('the price on the home page and shopping cart page is same', function() { expect(this.homePagePrice).to.equal(this.cartPagePrice) })
注意点:如果步骤内有异步操作,需要确保异步执行完成后再给this赋值,避免后续步骤取值为undefined。
方案3:模块级全局变量(不推荐)
在步骤定义文件顶部声明全局变量存储值,实现最简单,但多测试场景并行或者连续执行时会出现变量污染,除非每次场景执行前手动重置变量,否则不建议使用。
代码改造示例:
// 步骤文件顶部声明变量 let homePagePrice, cartPagePrice When('I go to home page I extract the price', () => { // 原有业务逻辑 homePagePrice = 100 }) When('I go to shopping cart page I extract the price', () => { // 原有业务逻辑 cartPagePrice = 100 }) Then('the price on the home page and shopping cart page is same', () => { expect(homePagePrice).to.equal(cartPagePrice) })
额外注意事项
如果提取的价格是带货币符号的字符串(比如¥100、$99),需要先做格式化转为数字类型再做对比,避免类型差异导致断言失败。
内容的提问来源于stack exchange,提问作者Sweety
相关产品推荐
相关产品推荐

