Cypress:如何保存变量并在以后使用它进行比较



我有一个div,它的值为15,000,可以由检索

cy.get('.population').invoke('text').then((numbers) =>{
let people = parseInt(numbers.replaceAll(',',''))
cy.wrap(people).as('population')
})

然而,我现在需要在另一个div中获得另外两个值,然后比较它们以确保它们相等。然而,这是有效的,在成功断言后立即抛出此错误cy.then() failed because you are mixing up async and sync code. In your callback function you invoked 1 or more cy commands but then returned a synchronous value. The value you synchronously returned was: {__flags: Object{5}}

这是整个代码。

cy.elem('population').invoke('text').then((num) =>{
let totalResidents = parseInt(num.replaceAll(',',''))
cy.wrap(totalResidents).as('population')
})
cy.get('@population').then((population) => { 
cy.get(`div[col- 
id=${columns.totalResidents}]`).find('span').find('div').then(($divs) => {
const nums = [...$divs].map(div => div.innerText)
const zcta1Pop = parseInt(nums[1].replaceAll(',',''))
const zcta2Pop = parseInt(nums[2].replaceAll(',',''))
const totalPop = zcta1Pop + zcta2Pop
return cy.expect(population).to.eq(totalPop) //successful assertion 15000 = 15000 but then fails right after
})

第二对div可以用表示

<span>
<div style="margin-left: 10px;">
<div>7,000</div>
</div>
</span>
<span>
<div style="margin-left: 10px;">
<div>8,000</div>
</div>
</span>

奇怪的是,最后的断言是正确的assert expected 15000 to equal 15000,但随后抛出错误。有人知道这里发生了什么吗?

除非您有自定义命令,否则cy.expect()...是错误的语法。它应该只是expect()...,但你不能退货。

您不需要返回上一个.then()中的任何内容,因为您已经完成了断言。

如果在后面立即使用值,则不需要使用别名。

cy.elem('population').invoke('text')
.then((num) =>{
let totalResidents = parseInt(num.replaceAll(',',''))
return cy.wrap(totalResidents)
})
.then(totalResidents1 => { 
cy.get(`div[col-id="${columns.totalResidents}"]`)
.find('span').find('div')
.then(($divs) => {
const nums = [...$divs].map(div => div.innerText)
const zcta1Pop = parseInt(nums[1].replaceAll(',',''))
const zcta2Pop = parseInt(nums[2].replaceAll(',',''))
const totalResidents2 = zcta1Pop + zcta2Pop
expect(totalResidents1).to.eq(totalResidents2)
})
})

或使用别名

cy.elem('population').invoke('text')
.then(num => parseInt(num.replaceAll(',','')))
.as('totalResidents1')
cy.get(`div[col-id="${columns.totalResidents}"]`)
.find('span').find('div')
.then($divs => {
const nums = [...$divs].map(div => div.innerText)
const zcta1Pop = parseInt(nums[1].replaceAll(',',''))
const zcta2Pop = parseInt(nums[2].replaceAll(',',''))
const totalResidents2 = zcta1Pop + zcta2Pop
return cy.wrap(totalResidents2)
})
.as('totalResidents2')
cy.get('@totalResidents1')then(totalResidents1 => {
cy.get('@totalResidents2').then(totalResidents2 => {
expect(totalResidents1).to.eq(totalResidents2)
})
})

相关内容

  • 没有找到相关文章

最新更新