'Creating a variable in a Cypress test to store text on a page in order to compare it against text on a different page

I'm trying to create a variable in my cypress test that will allow me to store info from one web page for when I click a link and leave the page. I want to compare a word from this first page to a word on the second.

describe("Logged-in Item Page", () => {

 before(() => {
   cy.*login command*().then((*login stuff*) => {
     cy.website_login(*login info*);
   });
 });
 beforeEach(() => {
   cy.visit(Cypress.env("baseUrl") + "*URL*")
 });
 
 it("Verify My Store opens", () => {
       return new Cypress.Promise(resolve => {
         cy.get("*selector*").then($value => {
           const storeName = $value.text().split(' ')[0];
           resolve(storeName);
         });
         cy.log(storeName)
       });
   });
});

It is worth to mention that I tried putting var Storename; outside of this area and removing the var keyword inside to cy.get() part but still no luck. As well I tried doing const storeName instead.



Solution 1:[1]

Because of its asynchronous nature, when you call storeName outside the .then($value => { it happens that the callback hasn't been done yet, so the value is not assigned.

Instead, you can use Cypress promises, so Cypress will wait until the promises is resolved.

    it("Verify My Store opens", async () => {
        const storeName = await new Cypress.Promise((resolve) => {
            cy.get("selector").then($value => {
                resolve($value.text().split(' ')[0])
            })
        })
        cy.log(storeName)

   })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1