如何在Cypress中实现跨测试用例可访问的共享同一别名
Cypress跨用例共享单次生成别名的相关疑问
测试场景设计
需要在测试套件中实现以下流程,核心约束是:所有测试用例必须共用同一个$dateTime值,全流程仅生成一次,绝对不能放在beforeEach钩子中每次测试前重新生成。具体流程为:
- 前置钩子阶段生成字符串格式的时间戳变量
$dateTime - 测试1:校验系统中不存在买家名为该时间戳的订单
- 测试2:创建订单,将该时间戳设置为买家姓名
- 测试3:校验系统中已存在买家名为该时间戳的订单
整个实现过程中查阅官方文档,没有找到对应的清晰实现路径。
待解答的问题
- 查阅官方文档「禁止操作」章节的别名相关说明,无法理解文档提到的「这类写法会让代码绕圈子」具体指什么问题
- 目前已经写出了可以正常运行的实现代码,存在两点困惑:
- 这种被官方明确标注不推荐的写法,会不会导致测试运行不稳定、是否属于反模式?实际使用过程中感觉这套写法简洁高效,和官方的不推荐提示存在落差
- 如果换用fixture存储这个公共值,能带来什么额外优势?
现有可正常运行的实现代码
context( 'Buy product' , function () { let dateTime = new Date(); let dateTimeStr = dateTime.toLocaleDateString('en-GB', { year: 'numeric', day: 'numeric', month: 'short', hour: 'numeric', minute: 'numeric', second: 'numeric' }); dateTimeStr = dateTimeStr.replaceAll( ', ', '--' ); dateTimeStr = dateTimeStr.replaceAll( ' ', '-' ); dateTimeStr = dateTimeStr.replaceAll( ':', '' ); beforeEach( () => { cy.wrap( dateTimeStr ).as('dateTimeStr'); }); it( 'Order with DateTime DOES NOT exists', () => { cy.visit( 'https://example.org/dashboard/orders' ); cy.get( "@dateTimeStr" ) .then( (dateTimeStr) => { cy.contains( dateTimeStr ).should('not.exist'); }); }); it( 'Buy product', function() { cy.visit( 'https://example.org/product/test' ); // 省略中间业务操作步骤 cy.get( '#first_name' ).type( this.dateTimeStr ); // 省略表单提交流程 cy.get('#submit_order').click(); }); it( 'Order with DateTime exists', () => { cy.visit( 'https://example.org/dashboard/orders' ); cy.get( "@dateTimeStr" ) .then( (dateTimeStr) => { cy.contains( dateTimeStr ).should('exist'); }); }); });
内容的提问来源于stack exchange,提问作者Zeth
相关产品推荐
相关产品推荐

