zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    spring boot RESTfuldemo测试类
    再谈Redirect(客户端重定向)和Dispatch(服务器端重定向)
    HTTP协议解析
    HTTP协议详解(真的很经典)
    JMeter进行简单的数据库(mysql)压力测试
    LoadRunner利用ODBC编写MySql脚本
    性能瓶颈的分析
    bug的处理流程
    Loadrunner11 录制手机App脚本多种方法介绍
    利用fiddler录制脚本
  • 原文地址:https://www.cnblogs.com/landhu/p/15753437.html
Copyright © 2011-2022 走看看