如何访问 Cypress 中您希望更改的文本的先前值?

问题描述 投票:0回答:1

我正在将 Cypress 从版本 8 升级到版本 13。在版本 8 中,我能够执行以下操作:

cy.getBySel('mealList-totalCalories').invoke('text').as('totalCals');

这会访问一个值的原始值,一旦将新项目添加到餐食列表中,该值就会发生变化。一旦卡路里值发生变化,我想确保新值等于之前的值加上所添加项目的卡路里值。这曾经有效:

cy.get('@totalCals').then((totalCals) => {
  console.log(totalCals) // This used to equal the original value, 2020, now is 2300.
  const expected = parseInt(totalCals) + 280;
  cy.getBySel('mealList-totalCalories').should('have.text', expected);
});

看来 Cypress 之前存储了

totalCals
的原始文本值,我可以稍后访问。然而,现在
totalCals
值已经等于之前的值 + 280,这让我认为 Cypress 只是再次运行之前的查询来访问当前值。

是否有一种新方法可以在 Cypress 中存储元素的文本以供以后访问?

cypress
1个回答
0
投票

是的,您的假设是正确的,赛普拉斯重新运行查询以避免过时的元素:https://docs.cypress.io/guides/core-concepts/variables-and-aliases#Stale-Elements

但是,您可以简单地将 then 表达式向上移动到第一个命令来自己捕获值:

cy.getBySel('mealList-totalCalories').invoke('text').then(totalCals) => {
  console.log(totalCals) // This should be 2020 now

  //do the other stuff that somehow changes the totalCals

  const expected = parseInt(totalCals) + 280;
  cy.getBySel('mealList-totalCalories').should('have.text', expected);
});
© www.soinside.com 2019 - 2024. All rights reserved.