Home > Net >  Use a variable outside of a function in Cypress
Use a variable outside of a function in Cypress

Time:02-14

I want to use a value that i got from a website and stored in a variable outside of a "within" function to comapre it with another value.

cy.get('.TableCloumn_3')
    .within($tr => {
     cy.get('[]').then(($span) => {

    const relRep = $span.text();
   
     cy.log(relRep);
      })
    })
    
  
   cy.log(relRep) 
    
  })

The first cy.log for relRep prints me the value but the second one does not. When I change from it from cont to var it also gives me an empty log. How can i use this value outside the function?

CodePudding user response:

You can initialize a variable at the top level and assign it inside the function

let foo

function bar() {
  foo = "1"
}
bar()
console.log(foo)

CodePudding user response:

Referring to your example, you can already declare relRep before the first cy.get() and then just initialize it later within the cy.within() like:

let relRep;

cy.get('.TableCloumn_3').within(($tr) => {
  cy.get('[]').then(($span) => {
    relRep = $span.text();

    cy.log(relRep);
  });
});

cy.log(relRep);

This will allow you to also access the value of relRep in the lower cy.log().

  • Related