https://cypress.io logo
Environment Scope Issue
# i-need-help
e
I'm new to Cypress and I have an issues with scope that I'm not quite understanding. I have a describe block with a beforeEach that runs a custom login command and then visits the application under test. The custom login command sets the token as an environment variable (which gets used by cy.intercept to inject into the header for every request to the baseUrl domain). The token and intercept works fine. I have a test that decodes that token and checks some of the elements. This all works fine until I wanted to move the test into another describe block which doesn't have the beforeEach step. When I do this, the token environment variable isn't available to that block of code and I can't work out why. Sounds like something to do with scope, but not sure what. If I cy.log the variable within the custom command, I know its being set at this point. The new describe block only has one test in it. It repeats the same login step, and visits the home page (which still works, therefore the token is being injected correctly). The next line of code just logs the entire Cypress.Env() and I can see its missing the token value. Why is the available if i use a beforeEach, but not in an indivdual test. This works.
Copy code
JavaScript
  beforeEach(() => {
    cy.login();
    cy.visit("/");
  });

  it('Correct user is logged in', () => {
       cy.log(JSON.stringify(Cypress.env()));
       // the token set in the cy.login() command is present
  });
This doesn't.
Copy code
JavaScript
  it.only('Correct user is logged in', () => {
      cy.login();
      cy.visit("/");
      cy.log(JSON.stringify(Cypress.env()));
      // the token set in the cy.login() command is not present
      // but all of the hardcoded enviroment variables are
  });
g
e
@gray-kilobyte-89541 Thanks, sort of makes sense. I'll have a go at reworking it.
@gray-kilobyte-89541 Sorry, it sort of makes sense and I get the concept at a high level in relation to the async nature, but I'm confusing myself on how to apply it to the environment variable as I'm not chaining it off a cy.get command. How should I be delaying this command until I'm sure the cy.login() request has fully completed and the environment variable has a value?
g
Copy code
js
it.only('Correct user is logged in', () => {
      cy.login();
      cy.visit("/").then(() => {
         // by now previous commands have finished
         cy.log(JSON.stringify(Cypress.env()));
       })
});
e
Thank you again. That works perfectly.
3 Views