Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use value of var which is set inside .then() outside of .then()?

I want to use a value of a var that is set inside of .then() in the outer scope

I tried

let numOfDropdownFields = 0;
cy.get("dropdown")
  .find("button")
  .its("length")
  .as("len")
  .then(($len) => {
    cy.log("No. of buttons:" + $len);
    numOfDropdownFields = $len;
    cy.get("@len").should("eq", numOfDropdownFields);
    cy.log(numOfDropdownFields);
  });
cy.log(numOfDropdownFields);

The first log prints: No. of elements: 14

The second log: 14

And the third log: 0

How can I see the value 14 outside the .then() callback?

like image 352
Raziel Zohar Avatar asked Sep 05 '25 03:09

Raziel Zohar


1 Answers

What you are trying to achieve is considered an antipattern in cypress. Generally you should do everything you want to do with that Variable inside the .then(). Make sure to use Syntax like: .then() => {all your code in here}.

Look here for Reference: https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Aliases

Also you can Use Aliases like you already did with .as('len').

like image 176
Henrik Avatar answered Sep 07 '25 23:09

Henrik