首页 > 解决方案 > 赛普拉斯:变量没有看到我在跑步者中看到的文本变化

问题描述

更新: 我会留下这个,以防其他人做同样的事情,但是循环在赛普拉斯中不起作用,因为赛普拉斯使用异步函数,我通过添加一个新的自定义命令来解决它,该命令检查文本是否存在,然后递归调用如果为真,则自定义命令

我正在尝试在给定的选择器中存在一些文本(“处理”)时重新加载页面以及您想要做的尝试:

var textFound = Cypress.$(selector).text();
cy.log(textFound) // For this example this is outputting all the text from a tr element I've passed to it

while (textFound.includes(text) && current_attempt <= attempts) {
  cy.log(`we have current attempt: ${current_attempt} `)
  cy.log(`we have selector: ${selector} `)
  cy.log(`we have text found: ${textFound}`)
  cy.log(`we are looking for: ${text}`) // These are outputting the correct values I expect to see the first time round the loop.

  cy.log(`We have text found = ${textFound.includes(text)}`) // outputs true 
  cy.log('reload page clear textfound then set again')
  cy.reload(true);
  textFound = 'Cleared'
  cy.log(`we have text found: ${textFound}`) // outputs Cleared
  cy.log(`Get textFound again`)
  textFound = Cypress.$(selector).text();
  cy.log(`we have text found: ${textFound}`) // Outputs the tr again
  cy.log('wait 30 seconds')
  current_attempt++
  cy.wait(30000);
}

问题是当我最终在大约 1 分钟后运行测试时,我可以在 Cypress 运行器中看到 TR 不再包含文本“处理中”,并且它不存在于页面上的任何其他位置,但是当我再次在循环中设置 textFound它仍然包含“处理”并且不显示“成功”,这是我在赛普拉斯跑步者中看到的。

谁能想到代码没有接受更改但我可以在跑步者中看到的原因?

标签: javascriptjquerycypress

解决方案


您的代码不起作用的原因是,因为赛普拉斯在测试开始之前声明的变量只是,并且在代码中不可访问,除非在回调或别名中声明和使用。另一方面,它适用于像对象/数组这样的引用。

要存储变量,我使用别名或对象:

let variables = {}
cy.get('elementSelector')
   .then($el => {
      //as allias
      cy.wrap($el.text()).as('variableName')

      //As object key
     variables.variableINeed = $el.text()
   })

// To call the variable as allias
cy.get('@variableName')
  .then(variable => {//code to use it})   

//To call the variable from object
cy.get('elementToCheck')
   .should('contain', variables.variableINeed)

推荐阅读