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
  • 相关阅读:
    微软并行编程类库Parallel Extensions初探 Part1 (转)
    一些很酷的.Net技巧(上)
    【Silverlight】Silvelright端获取托管web项目中xap的路劲
    【Silverlight】Silvelright获取web端的xml
    博客开始第一天
    asp.net过滤HTML方法
    程序员应该懂的道理
    生成缩略图
    转:用自定义IHttpModule实现URL重写
    android 之helloword
  • 原文地址:https://www.cnblogs.com/landhu/p/15753437.html
Copyright © 2011-2022 走看看