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

如何在Cypress中跨测试用例存储确认号用于断言?

跨测试用例传递确认号的解决方法

你遇到的问题是Cypress中每个it测试块独立执行,且Cypress命令为异步机制,导致全局变量confirmationNumber在第二个测试用例执行时要么未完成赋值,要么因测试上下文重置而丢失。以下是几种可行的解决方式:

方法1:使用Cypress环境变量存储

Cypress环境变量可跨测试用例、跨测试文件共享,适合存储这类临时传递数据:

describe("confirmation number across tests", () => {
  it("get confirmation number", () => {
    cy.visit('https://coffee-cart.app/')
    cy.get(':nth-child(2) > h4')
      .invoke('text')
      .then((text) => {
        const confirmationNumber = text.trim();
        cy.log('Captured Confirmation Number:', confirmationNumber);
        // 将值存入环境变量
        Cypress.env('confirmationNumber', confirmationNumber);
      });
  });

  it("use confirmation number", () => {
    cy.visit('https://testautomationpractice.blogspot.com/')
    // 从环境变量中取出值
    cy.get('#name').type(Cypress.env('confirmationNumber'));
  });
})

方法2:使用文件读写持久化数据

如果需要在多个测试文件间传递数据,可通过cy.writeFile将值写入本地文件,再用cy.readFile读取:

describe("confirmation number across tests", () => {
  it("get confirmation number", () => {
    cy.visit('https://coffee-cart.app/')
    cy.get(':nth-child(2) > h4')
      .invoke('text')
      .then((text) => {
        const confirmationNumber = text.trim();
        cy.log('Captured Confirmation Number:', confirmationNumber);
        // 写入到指定路径的文件中
        cy.writeFile('cypress/fixtures/confirmation.json', { number: confirmationNumber });
      });
  });

  it("use confirmation number", () => {
    cy.visit('https://testautomationpractice.blogspot.com/')
    // 读取文件中的值并使用
    cy.readFile('cypress/fixtures/confirmation.json').then((data) => {
      cy.get('#name').type(data.number);
    });
  });
})

注意事项

  • 不建议将两个测试步骤合并到同一个it块,这会破坏测试用例的独立性,不利于问题定位。
  • Cypress的别名(as())仅在当前it块作用域内有效,无法跨测试用例共享,因此之前用别名的方式无法实现需求。

内容的提问来源于stack exchange,提问作者gopencyprep

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 06:50:57