Cypress - cant get content of a span

Viewed 605

Im trying to check the content of a span containing a calculated price like this:

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

currentPrint always comes out ''.

I can get a value in the browser console:

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

and I can see the value in the Cypress console.

The angular html is like:

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

Ive tried sprinkling cy.wait(x) herw and there but that doesn't help.

Anyone got a suggestion?

Thanks

1 Answers

This problem is cy.log() is evaluating the value of currentPrice early, before the cy.get() runs.

Defer it by chaining as a sub-command

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

Not sure why they do it that way. Obviously cy.wrap() needs to do late evaluation because it's purpose is to capture a calculated value but why does cy.log() not also do late evaluation.

Short answer, don't use cy.log() to debug, use console.log.


Saving value to this

Use function not () =>

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