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

before中定义的alias无法在首个测试后的beforeEach中访问的问题

问题原因

Cypress的别名(@xxx)是**绑定到单个测试用例(it块)**的作用域,每个测试执行完毕后,Cypress会自动清除当前测试的所有别名、状态和上下文。

你在before钩子中定义的别名,只会存在于第一个测试用例的上下文中。当第一个测试结束后,该别名就被销毁了,所以第二个测试的beforeEach执行cy.get('@testVariable')时,找不到已注册的别名。

解决方案

提供三种可行的解决方法,根据需求选择:

方法1:将别名定义移到beforeEach中

让每个测试执行前都重新创建别名,确保beforeEach能稳定访问:

describe('Testing before and beforeEach issue', () => {
  context('testing before and beforeEach', () => {
    beforeEach(() => {
      cy.wrap("TESTING 123").as("testVariable")
      cy.get("@testVariable").then((testVariable) => {
        cy.log(`THIS IS A TEST: ${testVariable}`)
      })
    })

    it('Testing the variable one time', () => {
      cy.log("THIS IS LOG 1")
    })

    it('Testing the variable a second time', () => {
      cy.log("THIS IS LOG 2")
    })
  })
})

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

如果变量是跨测试共享的固定值,用环境变量保存,不受测试上下文清除影响:

describe('Testing before and beforeEach issue', () => {
  context('testing before and beforeEach', () => {
    before(() => {
      Cypress.env('testVariable', "TESTING 123")
    })

    beforeEach(() => {
      const testVariable = Cypress.env('testVariable')
      cy.log(`THIS IS A TEST: ${testVariable}`)
    })

    it('Testing the variable one time', () => {
      cy.log("THIS IS LOG 1")
    })

    it('Testing the variable a second time', () => {
      cy.log("THIS IS LOG 2")
    })
  })
})

方法3:使用共享上下文this

注意要把钩子和测试的箭头函数改成普通函数,Cypress会在这些函数中绑定一个共享上下文对象:

describe('Testing before and beforeEach issue', () => {
  context('testing before and beforeEach', function() {
    before(function() {
      this.testVariable = "TESTING 123"
    })

    beforeEach(function() {
      cy.log(`THIS IS A TEST: ${this.testVariable}`)
    })

    it('Testing the variable one time', function() {
      cy.log("THIS IS LOG 1")
    })

    it('Testing the variable a second time', function() {
      cy.log("THIS IS LOG 2")
    })
  })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:50:48