【问题标题】:Cypress - cant get content of a span赛普拉斯 - 无法获得跨度的内容
【发布时间】:2021-09-16 22:34:23
【问题描述】:

我正在尝试检查包含这样计算价格的 span 的内容:

    let currentPrice = ''; 
    cy.get('[data-cy="orgsub-price-span"]', { timeout: 2000 }).then(($ele) => {
      currentPrice = $ele.text();
      cy.log(`'Current Price : ${currentPrice}`);
    });

currentPrint 总是输出 ''。

我可以在浏览器控制台中获取一个值:

document.querySelector('[data-cy="orgsub-price-span"]').textContent;

我可以在赛普拉斯控制台中看到该值。

angular html 是这样的:

  <span data-cy="orgsub-price-span" *ngIf="!calculating">
    {{ (totalCharge - discount + totalTax) }}
  </span>

我试过在那儿撒上 cy.wait(x) herw,但没有用。

有人有建议吗?

谢谢

【问题讨论】:

    标签: angular cypress


    【解决方案1】:

    这个问题是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 而不是() =&gt;

    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
    })
    

    【讨论】:

    • 很棒的答案@Paolo。谢谢!对我对赛普拉斯的理解有很大帮助。
    猜你喜欢
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2022-08-18
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多