Kashif nadeem
Kashif nadeem

Reputation: 181

cypress: variable scope outside the then block. I am facing issue

I have issue with scope outside the then block. Need help of exerts

  it("Badges Count", () => {
    var totalBadges
    cy.get("div:nth-child(4) > span.quick-stat-figure").then($el => {
      cy.get("div.profile-quick-stats > div:nth-child(4)").click();
        totalBadges = $el.get(0).textContent;
      cy.log("Total Badges", totalBadges); // scope is working here       
  });

  cy.log("Badeges", totalBadges)  // scope is not working here
});

Upvotes: 2

Views: 3768

Answers (1)

Sorin D.
Sorin D.

Reputation: 91

In cases such as these I like to use aliases.

Simply wrap() your value, whatever it is, and save it with an alias, then get() and use it wherever you need.

Based on your example it should look something like this:

it("Badges Count", () => {
    // var totalBadges - you don't need this anymore
    cy.get("div:nth-child(4) > span.quick-stat-figure").then($el => {
      cy.get("div.profile-quick-stats > div:nth-child(4)").click();
      let totalBadges = $el.get(0).textContent;
      cy.wrap(totalBadges).as('totalBadges'); 
      // this is now accessible globally via get('@totalBadges')         
  });

  cy.get('@totalBadges').then((myBadges) => {
    cy.log("Badeges :"+ myBadges)  // should work just fine
  }
  
});

I know it might not look very intuitive, but working with Cypress you will rarely ever need to use variables.

You can check out the Cypress documentation on aliases here.

Upvotes: 3

Related Questions