赛普拉斯:将值存储在变量中

Cypress: store value in a variable

我想在变量中存储一个 td 值。为什么此代码不起作用?

let storedValue;
cy.get('tbody>tr:nth-child(1)>td:nth-child(3)').invoke('text').then(text => 
{
  storedValue = text;
})
cy.contains(storedValue).should('exist');

它returns "cy.contains()只能接受字符串、数字或正则表达式"

更好的方法是使用 aliases

cy.get('tbody>tr:nth-child(1)>td:nth-child(3)').invoke('text').as('storedValue')

cy.get('@storedValue').then((storedValue) => {
  //Access storedValue here
  cy.log(storedValue) //prints value
})

或者如果你只是想检查元素是否存在,你可以直接这样做:

cy.get('tbody>tr:nth-child(1)>td:nth-child(3)').should('exist')

关于为什么你的代码不工作的问题,是因为 javascript 异步工作,所以不是先获取文本的代码,而是先执行 contains 语句,失败的原因是那storedValue里面什么都没有,简而言之就是undefined。要修复,您必须添加 then() 以便代码 运行s 按照我们想要的顺序排列在 运行 中。

let storedValue
cy.get('tbody>tr:nth-child(1)>td:nth-child(3)')
  .invoke('text')
  .then((text) => {
    storedValue = text
  })
  .then(() => {
    cy.contains(storedValue).should('exist')
  })