首页 > 解决方案 > 在多个“it”语句中使用变量来跟踪赛普拉斯的变化

问题描述

我正在使用 Cypress ( https://www.cypress.io/ ) 来测试一个应用程序,该应用程序跟踪在用户限制内完成的 API 调用量。该测试在 API 调用之前和调用之后再次检查限制。测试的目的是查看调用后限制是否发生变化。

限制在屏幕上呈现。我尝试将值存储在一个变量中。在进行 API 调用之后,我想比较之前和之后的值。

已经尝试使用 const 和 let 将其存储在变量中,但两者都不能在 'it' 语句之外工作。

it('should get the limit value before doing an api call', ()=> {
            cy.get('.bar__legend')
                .contains('used')
                .then(($usage) => {
                    let usageTxt = $usage.text()
                    let words = usageTxt.split(' ')
                    let usageBefore = words[0]
                })
        });


it('should do an API call twice', () => {
            // do a API call twice
}

it('should get the limit value after doing an api call', ()=> {
            cy.get('.bar__legend')
                .contains('used')
                .then(($usage) => {
                    let usageTxt = $usage.text()
                    let words = usageTxt.split(' ')
                    let usageAfter = words[0]

                    cy.log(usageBefore)
                    cy.log(usageAfter)
                })
        });

我尝试的另一种方法

it('should increase the limit after an api call', ()=> {
            cy.get('.bar__legend')
                .contains('used')
                .then(($usage) => {
                    let usageTxt = $usage.text()
                    let words = usageTxt.split(' ')
                    let usageBefore = words[0]
                })

            cy.visit('apilink')
            cy.wait(2000)

            cy.visit('apilink')
            cy.wait(2000)

            cy.get('.bar__legend')
                .contains('used')
                .then(($usage) => {
                    let usageTxt = $usage.text()
                    let words = usageTxt.split(' ')
                    let usageAfter = words[0]

                    cy.log(usageBefore)
                    cy.log(usageAfter)
                })
        })

我希望这两个变量都有一个值,但测试失败,因为“usageBefore”变量不存在。

标签: cypress

解决方案


我相信诀窍是在it()'s 之外定义变量。因此语法看起来像这样:

var usageBefore
var usageAfter

describe('description of the test', () =>{
  it('This uses the variable', () =>{
    cy.get('.bar__legend')
      .contains('used')
      .then(($usage) => {
        let usageTxt = $usage.text()
        let words = usageTxt.split(' ')
        usageBefore = words[0]
      })
  })
  it('should get the limit value after doing an api call', ()=> {
    cy.get('.bar__legend')
      .contains('used')
      .then(($usage) => {
        let usageTxt = $usage.text()
        let words = usageTxt.split(' ')
        usageAfter = words[0]

        cy.log(usageBefore)
        cy.log(usageAfter)
      })
})

推荐阅读