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

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