Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a variable/text to use later in Cypress test?

The cypress docs(https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Elements) are pretty unclear on how alias and variables can be used to store information during a test.

I'm trying to store the text of a div on one page to use later, for example:

// let vpcName;
it('Store current name to use later', () => {
  // save name for later use - doesn't work
  // cy.get('#value').then(elem => {
  //   vpcName = Cypress.$(elem).text;
  // });

  // using alias - also doesn't work
  cy.get('#value')
    .invoke('text')
    .as('vpcName');
});
  
it('Use previous value to return to correct page', () => {
  cy.contains(this.vpcName).click();
});
like image 290
Ken M Avatar asked Dec 04 '19 20:12

Ken M


3 Answers

I just came across this article that explains how and why you store a variable and then use it later in the "Cypress way":

https://www.stevenhicks.me/blog/2020/02/working-with-variables-in-cypress-tests/

In respect to how it should work, here is my example which first, collects the message (the message is shown for only 3 secs then disappears). Secondly, it gets the value using the @ sign. Lastly my code passes the stored message through to an empty function constructed to assert that the value Portsmouth is contained within the message.

it('Current Port change', () => {
  cy.get('#viewport').find('div[id=message]').then(message => {
    let wags = message;
    cy.wrap(wags).as('wags')
  });

  cy.get('@wags').then(wags => {
     expect(wags).to.contain("Portsmouth")
  });
});

let me know if you need further clarification

like image 68
new_tester Avatar answered Nov 06 '22 17:11

new_tester


Try this:

cy.get('button').then(($btn) => {
  const txt = $btn.text()
  // $btn is the object that the previous command yielded
})

Source: https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Return-Values

like image 21
Punit Avatar answered Nov 06 '22 18:11

Punit


I had to resort to

  • writeFile
  • readFile

When I was trying to save cookies from one test to another in Cypress

like image 38
Zeth Avatar answered Nov 06 '22 17:11

Zeth