• 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

    Email:362299908@qq.com
  • 相关阅读:
    2.6、实战案例(三)
    2.5、实战案例(二)
    2.4、实战案例(一)
    2.3、视频采集(二):分辨率、摄像头切换、帧率、滤镜
    2.2、视频采集(一):初步采集
    2.1、列举媒体设备
    1.0、本章导读
    linux 下搭建vsftpd
    解决.net core 3.1跨域问题
    SQLServer for linux安装
  • 原文地址:https://www.cnblogs.com/landhu/p/15753437.html
Copyright © 2020-2023  润新知