How To Inject Environment Variables Into Cypress Tests

How to pass specific environment variables into Cypress tests.

Let's say you want to pass an environment variable with the user name into a Cypress test. Since the test runs in the browser, you cannot access the process.env.USERNAME directly. Instead you need to inject the variable using on of the several of the ways. Here is how I would do it:

Use .as-a.ini file

I would keep all passwords in a file .as-a.ini that is ignored by my source rules. Thus the sensitive information is never checked into the source control. For example, I would name the block of environment variables e2e-secrets

.as-a.ini
1
2
3
4
; https://github.com/bahmutov/as-a
[e2e-secrets]
CYPRESS_username=Joe
CYPRESS_password=123secret!

To inject these variables when starting Cypress, I would use my utility tool as-a that you can install globally or as a dev dependency

1
2
$ npm i -g as-a
$ as-a e2e-secrets npx cypress open

Cypress automatically reads all environment variables that start with CYPRESS_ prefix and makes them available in Cypress.env() object.

1
2
3
// spec file
Cypress.env()
// { username: 'Joe', password: '123secret!' }

You can also get each variable separately

1
2
3
// spec file
Cypress.env('username') // 'Joe'
Cypress.env('password') // '123secret!'

Watch how I use the as-a tool in this short video "Use Utility as-a To Load Multiple Secrets And Pass To Cypress"

Tip: read my blog post Keep passwords secret in E2E tests to make sure the tests don't reveal sensitive information.

Pass an entire object

If an environment variable CYPRESS_ has a JSON stringified object, it will be automatically decoded into an object. For example, let's put the user information into .as-a.ini file

.as-a.ini
1
2
[user]
CYPRESS_user={"username": "Joe", "password": "123secret!", "age": 42, "valid": true}

Now let's read this object when launching Cypress Test Runner

1
$ as-a user npx cypress open

You can see the entire parsed object in the env object in the projects settings tab

Injected and parsed env object

The test can confirm the object has what we expect to find:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// show full objects in the assertions message
// https://glebbahmutov.com/blog/cypress-tips-and-tricks/
// or use https://github.com/bahmutov/cy-spok
chai.config.truncateThreshold = 200

it('has a parsed JSON user object', () => {
const user = Cypress.env('user')
cy.wrap(user).should('deep.equal', {
username: 'Joe',
password: '123secret!',
age: 42,
valid: true,
})
})

Tip: want to confirm the types of the properties and not the values? Use cy-spok assertions.

This example comes from the repo bahmutov/cypress-as-a-example and is shown in the short video "Inject Entire Objects Into Cypress Tests Using as-a Utility"

See also