0

I am getting to a point that i can cy.log() the text that is inside that element but i can't find a simple solution where i can get that text, store it and manipulate it for later tests.

it('login to my eshop that uses virtual currency' , function() {
    cy.visit('my favorite shopping site')
    cy.get('#username').type('user')
    cy.get('#password').type('pass')
    cy.get('balance element').then(function(text1){
        cy.log(text1.text())
        ///I see the text but that's pretty much it.
    })
})

I do not need an assertion for this particular case. I am trying to get a current balance, do some purchase testing and compare initial balance with remaining balance.

Any suggestions would be greatly appreciated , spent couple of days searching, trying and editing but i am stuck do the async nature of cypress.

Vaios
  • 1
  • 2
  • Please see [Why cy.log Prints Nothing](https://glebbahmutov.com/blog/why-cy-log-prints-nothing/) for discussion about enqueuing commands. – Fody Mar 17 '22 at 23:48

4 Answers4

2

Try:

    cy.get('balance element').invoke('text').then((text) => {
      cy.wrap(text).as('balanceText');
    });

Do this in beforeEach then you can use it in further it-functions like this:

it('my test', function () {
  console.log(this.balanceText);
})
Michael K.
  • 1,738
  • 2
  • 17
  • 35
  • That is doing the same thing but i don't know how to pass the text to a usable variable after – Vaios Mar 17 '22 at 13:17
1

In your case, you can return the value from your then() command and have the value available in a subsequent command.

it('login to my eshop that uses virtual currency' , function() {
    cy.visit('my favorite shopping site')
    cy.get('#username').type('user')
    cy.get('#password').type('pass')
    cy.get('balance element')
      .then(function(text1){
        return text1.text()
    }).then(function(text) {
       // code that uses the `text` variable
    });

})
agoff
  • 5,818
  • 1
  • 7
  • 20
0

Option 1:

let balance;
it('Test case 1 Return variable', () => {
  cy.get("balance element").invoke("text").then(cy.log).then((text) => {
                balance = text;
                return text;
        })
});

it('Test case 2 Use variable', () => {
        
        cy.log(balance)
});

Option 2

let balance;
it('Test case 1 Return variable', () => {

 cy.get('balance element').invoke("text").then((text) => {
                cy.log("Text", text).then(() => {
                    balance = text;
                    return balance;
                })
  });
});

it('Test case 2 Use variable', () => {
        
        cy.log(balance)
});

Option 3 You can use the approach which the log:added event

// top of spec

const logs = []
Cypress.on('log:added', (log) => {
  const message = `${log.consoleProps.Command}: ${log.message}`
  logs.push(message)
})

Then in your it block

it('writes to logs', () => {

 cy.get('balance element').invoke('text').then((text) => {
                const balance = text
                cy.log('balance', balance)
                cy.writeFile('cypress/fixtures/logs.txt', balance)
   })
});
  • Niluka , thank you , your answers really helped me. Do you have any tips on how to convert a string to a number? parseInt worked for balance but not for the price of the product. I can only get the number with split but still i get NaN when i try to make calculations between the two. – Vaios Mar 17 '22 at 21:13
  • You can refer- https://stackoverflow.com/questions/1133770/how-to-convert-a-string-to-an-integer-in-javascript, https://dev.to/sanchithasr/7-ways-to-convert-a-string-to-number-in-javascript-4l – Niluka Monnankulama Mar 18 '22 at 04:15
  • seems i got the syntax wrong. Thanks again for your time and effort. – Vaios Mar 18 '22 at 10:07
0

Ok with the help of all your answers and about 1 day of trying this flow worked for me. I am leaving this edited snippet in case someone else finds it helpful. I am sure more experienced developers or testers can do that with a lot less lines.

    /// <reference types="cypress" />

  let balance;
  let productPrice;
  let productPricenum;
  let balanceAfter;
  let finalCalculation = balance - productPricenum;
  
 
  it('Buy a product and assign balance and cost variables', () => {

    ///Login proccess - custom commands
    cy.home()
    cy.login()
    

    ///Get your initial balance
      cy.get('balance element here').invoke("text").then(cy.log).then((text) => {
                    balance = parseInt(text);
                    return text;
                  })
    
    /// Get the products price from the product page, extract the price from the string and convert price string to int. Assign final calculation to variable
    /// Since i get the numbers from dynamic elements i had to parseInt one and split and parseInt the other to make numerical calcs
    cy.visit('product page')
    cy.get('product price element here').invoke('text').then(cy.log).then((text) => {
        
        productPrice = text.split(' ')[1];
        productPricenum = parseInt(productPrice);
        finalCalculation = balance - productPricenum;
        
      })

      ///Buy the product  - this will differ from case to case and perhaps needs more steps to the final purchase
      cy.get('element to click to purchase the product eg. buy now button').click()

      ///return to homepage after purchase in case the balance isn't auto-refreshed
      cy.home()
      
      ///Get your new balance again after the purhcase
      cy.get('balance element here').invoke("text").then(cy.log).then((text) => {
        balanceAfter = parseInt(text)
        return text;
        
        })
        
      });
 
  it('print out the variables just because you like to see what you got', () => {
    cy.log('My current balance is :' + balance)
    cy.log('Product costs: ' + productPrice)
    cy.log('After buying it i have:' + finalCalculation)
    cy.log('My new balance is now: ' + balanceAfter)
    console.log('Balance is a  ', typeof balance + '  and it is   ->' + balance)
    console.log('Product price is a  ', typeof productPrice + '   and it is    ->' + productPrice)
    console.log('Converted Product price is a  ', typeof productPricenum + '   and it is    ->' + productPricenum)
    console.log(`I must be left with : ${balance - productPricenum}`)
    console.log('My new balance is: ' + balanceAfter)
    
 })
    
 it('Assert that the deduction of the cost was proper by comparing the numbers', () => {expect(finalCalculation).to.equal(balanceAfter)})
Vaios
  • 1
  • 2