【问题标题】:Cypress | using variables declared in beforeEach hook柏树 |使用在 beforeEach 钩子中声明的变量
【发布时间】:2021-09-09 11:30:11
【问题描述】:

在我的 e2e 测试中,我在 beforeEach 挂钩中声明了一些变量,以便稍后在测试中使用它们。

目前的解决方案:

    beforeEach(() => {
      // some variables are declared here
      // using cy.wrap only for presentation purpose
      cy.wrap({ foo: 1 })
        .as('foo')
      cy.wrap({ bar: 2 })
        .as('bar')
    })

    it('some test', () => {
      cy.get('@foo')
        .then((foo) => {
          cy.get('@bar')
            .then((bar) => {
              // here I have access to these variables
            })
        })
    })

这很好,但是如果我有 10 个变量要传递给测试呢?然后我会有 10 个嵌套的 .then 看起来不太好。

我知道我可以使用letcontext 中声明这些变量,然后在测试中访问它们,但不推荐在赛普拉斯中处理变量的方式。

    let globalFoo
    let globalBar
    
    beforeEach(() => {
      // some variables are declared here
      // using cy.wrap only for presentation purpose
      cy.wrap({ foo: 1 })
        .then((foo) => {
          globalFoo = foo
        })
      cy.wrap({ bar: 2 })
        .then((bar) => {
          globalBar = bar
        })
    })

    it('some test', () => {
      // now I have access to them too
      cy.wrap(globalBar)
      cy.wrap(globalFoo)
    })

有没有办法将许多变量从 beforeEach 挂钩传递到测试并保持干净的代码?

【问题讨论】:

    标签: mocha.js cypress


    【解决方案1】:

    您可以使用 this.* 符号来访问 cypress 变量而无需 then 回调:

        beforeEach(() => {
          // some variables are declared here
          // using cy.wrap only for presentation purpose
          cy.wrap({ foo: 1 })
            .as('foo')
          cy.wrap({ bar: 2 })
            .as('bar')
        })
    
        it('some test', function() {
            // here I have access to these variables
            console.log(this.foo + this.bar)   
        })
    

    注意在it 语句中使用了函数回调,因为这在箭头回调中不起作用 (() => {})

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2016-04-17
      • 1970-01-01
      • 2021-05-25
      • 2019-02-03
      相关资源
      最近更新 更多