这个问题是cy.log() 在cy.get() 运行之前提前评估currentPrice 的值。
通过链接作为子命令来延迟它
let currentPrice = '';
cy.get('[data-cy="orgsub-price-span"]', { timeout: 2000 })
.then(($ele) => {
currentPrice = $ele.text();
cy.log(`Current Price : ${currentPrice}`) // early evaluation, logs ''
console.log(`Current Price : ${currentPrice}`) // late evaluation, logs value
cy.then(() => cy.log(`'Current Price : ${currentPrice}`)); // late evaluation, logs value
cy.wrap(currentPrice).as('currentPrice') // save to Cypress alias
})
.then() => {
cy.log(`Current Price : ${currentPrice}`) // late evaluation, logs value
})
// Using currentPrice later
console.log(currentPrice) // early evaluation, logs ''
cy.then(() => console.log(currentPrice)) // late evaluation, logs value
cy.then(() => cy.log(`'Current Price : ${currentPrice}`)); // late evaluation, logs value
// From alias
cy.get('@currentPrice').then(currentPrice => {
cy.log(`'Current Price : ${currentPrice}`); // late evaluation, logs value
})
不知道他们为什么这样做。显然cy.wrap() 需要进行后期评估,因为它的目的是捕获计算值,但为什么cy.log() 不也进行后期评估。
简答,不要使用cy.log()调试,使用console.log。
将值保存到this
使用function 而不是() =>
it('tests current price', function() {
cy.get('[data-cy="orgsub-price-span"]', { timeout: 2000 })
.then(function($ele) {
const currentPrice = $ele.text();
cy.wrap(currentPrice).as('currentPrice') // save to Cypress alias
})
// From alias, using `this`
cy.log(`Current Price : ${this.currentPrice}`) // late evaluation, logs value
})