2.9 KiB
title: env comments: true
Cypress.env allows you to get and set your environment variables.
This document covers the API for consuming your environment variables in your tests. The Environment Variable guide explains the 4 ways you can set them outside of your tests.
{% note info New to Cypress? %} Read about environment variables first. {% endnote %}
Cypress.env()
Returns all of your environment variables as an object literal.
Cypress.env( key )
Returns the value of a single environment variable by its key.
Cypress.env( key, value )
Sets an environment variable for a specific key.
Cypress.env( object )
Sets multiple environment variables.
No Arguments Usage
Get all environment variables.
// cypress.json
{
"env": {
"foo": "bar",
"baz": "quux"
}
}
Cypress.env() // => {foo: "bar", baz: "quux"}
Key Usage
Return just a single environment variable value.
// cypress.json
{
"env": {
"foo": "bar",
"baz": "quux"
}
}
Cypress.env("foo") // => bar
Cypress.env("baz") // => quux
Key Value Usage
Cypress allows you to change the values of your environment variables from within your tests.
{% note warning %} Any value you change will be permanently changed for the remainder of your tests. {% endnote %}
// cypress.json
{
"env": {
"foo": "bar",
"baz": "quux"
}
}
Cypress.env("host", "http://server.dev.local")
Cypress.env("host") // => http://server.dev.local
Object Usage
You can set multiple values by passing an object literal.
// cypress.json
{
"env": {
"foo": "bar",
"baz": "quux"
}
}
Cypress.env({
host: "http://server.dev.local",
foo: "foo"
})
Cypress.env() // => {foo: "foo", baz: "quux", host: "http://server.dev.local"}
Notes
Why use Cypress.env instead of cy.env?
As a rule of thumb anything you call from Cypress affects global state. Anything you call from cy affects local state.
Methods on cy are local and specific to a single test. Side effects from cy methods are restored between each test. We chose to use Cypress because changes to your environment variables take effect for the remainder of ALL tests.
Why would I ever need to use environment variables?
The Environment Variables guide explains common use cases.
Can I pass in environment variables from the command line?
Yes. You can do that and much more.
The Environment Variables guide explains the 4 ways you can set environment variables for your tests.