Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define variables in cypress.env.json

I want to define global variables for my tests of the selected application. I want to input them into one file - after reading the documentation I decided to use cypress.env.json.

https://docs.cypress.io/guides/guides/environment-variables.html#Option-1-cypress-json

As I see variables are imported correctly, but during the test, I get the error:

"TypeError: Cannot read property 'env' of undefined"

Any suggestions on how to fix that problem?

https://i.sstatic.net/K26vU.png

Test file:

describe('/register', () => {
    beforeEach(() => {
        cy.visit('/#/register')
    })

    it.only('requires username', () => {
        cy.get('input[type="email"]').Cypress.env('correctEmail')
        cy.get('input[type="password"]').Cypress.env('correctPassword')
        cy.get('button').contains('Sign in').click()
        cy.get('.error-messages').should('contain', 'username can\'t be blankis too short (minimum is 1 character)')
    })

cypress.env.json:

{
    "correctName": "Bob Ross",
    "incorrectName": "Bobbbbb",
    "correctEmail": "[email protected]",
    "incorrectEmail": "b@bbb",
    "correctPassword": "bobrosss",
    "incorrectPassword": "Oooooo" 
}
like image 327
Piecho3a Avatar asked Jun 07 '26 15:06

Piecho3a


1 Answers

To answer your original question, the cypress.env.json file needs to be placed inside the root of your project, right next to the cypress.json file.

By creating a separate cypress.env.json file you're able to access nested values, like so:

//cypress.env.js
{
    "user": {
        "username": "Jane",
        "password": "SuperPassword",
        "someOtherData": "veryImportantData"
    }
}

and then

//somewhere in myCypressTest.spec.ts
Cypress.env("user").username      //returns "Jane"
Cypress.env("user").password      //returns "SuperPassword"
Cypress.env("user").someOtherData //returns "veryImportantData"

It's not really documented accurately anywhere unfortunately. I didn't need to change any paths, just moved the cypress.env.json outside the Cypress folder where I had originally placed it, and it started working.

like image 134
jSun Avatar answered Jun 10 '26 05:06

jSun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!