cypress中变量的处理

最近学习cypress,框架有好有坏,不做评价。

在使用参数时,如果之前是使用java或python的同学的话,在cypress参数中会相同不习惯。先来看一个简单的例子

it('stores value in variable', ()=>{
        let id
        cy.request('https://jsonplaceholder.cypress.io/comments')
          .then(res =>{
              id = res.body[0].id
              cy.log(id)
          })
        cy.visit('/comments/' + id)
        cy.log(id)
    })

这样一段代码,按正常在python中,最后2行,id是有值的。但是,在实际运行中,参数为undefined

 

 为什么会这样呢,这是因为 cypress命令链决定的。

那么如果我想获取这个值,该怎么处理呢?

有以下几种解决方案:

方案一:直接把visit放入then中

it("solution1", ()=>{
        let id
        cy.request('https://jsonplaceholder.cypress.io/comments')
          .then(res =>{
              id = res.body[0].id
              cy.log(id)
              cy.visit('/comments/' + id)
          })
    })

方案二:参数定义放在用例外

    let ipx
    it('assign new value', ()=>{
        cy.request('https://jsonplaceholder.cypress.io/comments')
          .then(res =>{
              ipx = res.body[0].id
          })
    })

    it('user variable', () =>{
        cy.log(ipx)
        cy.visit('/comments/' + ipx)
    })

这种方案不太妥,因为如果前一个用例失败了,必定影响后面的用例

 

方案三:使用before

let id 

beforeEach( () => {
  cy.request('https://jsonplaceholder.cypress.io/comments')
    .then( res => {
    id = res.body[0].id 
  })
})

it('use variable', () => {
  cy.visit('/comments/' + id) 
})

每个用例执行前都去更新id变量。

 

方案四:使用aliases

it('use alias', () => {

  cy.request('https://jsonplaceholder.cypress.io/comments')
    .as('board') // 定义使用alias
  
  
  //...

  cy.get('@board') // 使用
    .its('body')
    .then( body => {
    
      cy.visit('/board/' + body[0].id)

    })

})

代码会简洁很多

方案五:使用aliases和before

beforeEach( () => {
  cy.request('https://jsonplaceholder.cypress.io/comments')
    .as('board')
})

it('use variable', function() {
  cy.visit('/comments/' + this.board.body[0].id) 
})

需要注意的是,this.* 不能用于()=>这样的表达式中

 

更多详细使用方法参考:https://docs.cypress.io/guides/core-concepts/variables-and-aliases#Return-Values

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章