Home > Software engineering >  Cypress doesn't find Environment variable from cypress.env.json
Cypress doesn't find Environment variable from cypress.env.json

Time:08-24

I have the following folder structure:

tests
  cypress.env.json
  cypress
    fixtures
    integration
      test
        test.spec.ts
    plugins
    support

I have missed out the for the question unnecessary files.
So my cypress.env.json looks like this:

{
  "loginTestStage": {
    "admin": {
      "username": "value1",
      "password": "value2"
    },
    "user": {
      "username": "value3",
      "password": "value4"
    }
  },
  "vatid" : {
    "x1": "value5",
    "x2": "value6",
    "x3": "value7",
    "x4": "value8"
  }
}

Now I try to access the env variable in the test.spec.ts file:

describe('Login', () => {
    const usernameInput = '[formcontrolname="username"]';
    const passwordInput = '[formcontrolname="password"]';
    beforeEach(() => {
        cy.visit(url)
    })

    it('Allow users with valid credentials to login', () => {
        const { username, password } = Cypress.env('loginTestStage').admin;
        cy.get(usernameInput).type(username);
        cy.get(passwordInput).type(password);
        ...

    })
})

When I try to run the test I always get this error here:

Cannot read properties of undefined (reading 'admin')

So the value from the Env variable can't be found. How can this be solved?
Thanks in advance

CodePudding user response:

It will work if you move cypress.env.json to the project root.

Just like cypress.config.js (v10) or cypress.json (v9) there is no configuration path for this env file, it is assumed to be at the project root.

  • Related