dx584905
dx584905

Reputation: 311

Cypress: store value in a variable

I want to store a td value in a variable. Why this code doesn't work?

let storedValue;
cy.get('tbody>tr:nth-child(1)>td:nth-child(3)').invoke('text').then(text => 
{
  storedValue = text;
})
cy.contains(storedValue).should('exist');

It returns "cy.contains() can only accept a string, number or regular expression"

Upvotes: 2

Views: 4136

Answers (1)

Alapan Das
Alapan Das

Reputation: 18634

A better approach would be to use aliases.

cy.get('tbody>tr:nth-child(1)>td:nth-child(3)').invoke('text').as('storedValue')

cy.get('@storedValue').then((storedValue) => {
  //Access storedValue here
  cy.log(storedValue) //prints value
})

Or if you just want to check whether the element exists or not, you can directly do:

cy.get('tbody>tr:nth-child(1)>td:nth-child(3)').should('exist')

And for the question of why is your code not working, its because javascript works asynchronously, so instead of the code that gets the text first, the contains statement is executed first and the reason it fails is that storedValue doesn't have anything in it, in short, it is undefined. To fix then you have to add then() so that the code runs in a sequence we intend it to run in.

let storedValue
cy.get('tbody>tr:nth-child(1)>td:nth-child(3)')
  .invoke('text')
  .then((text) => {
    storedValue = text
  })
  .then(() => {
    cy.contains(storedValue).should('exist')
  })

Upvotes: 3

Related Questions