Exit course
Chapter 7 of 11 Beginner 6 min read 3 quick checks Updated

Cypress Configuration, Environment Variables and Retries

Watch this chapter Starts at 4:21 in the 9:03 course video.
On this page
  1. The configuration file
  2. setupNodeEvents and cy.task
  3. Environment variables
  4. Test retries

A suite that only runs against one hard-coded URL, with secrets committed to the repository, does not survive contact with a team. This chapter covers the configuration file, how to point the same specs at different environments, where secrets go, and how test retries work.

The configuration file#

Here is the course's cypress.config.js at this point:

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    baseUrl: 'https://example.cypress.io',
    defaultCommandTimeout: 4000,
    retries: { runMode: 2, openMode: 0 },
    setupNodeEvents(on, config) {
      on('task', {
        log(message) {
          console.log(message)
          return null
        },
      })
    },
  },
})

defineConfig does nothing at runtime; it gives your editor autocompletion for every option. Options inside e2e apply to end-to-end tests only; options at the top level apply to both e2e and component testing (chapter 7). The ones you will change most often:

Option Default What it does
baseUrl none prefix for relative cy.visit and cy.request paths
specPattern cypress/e2e/**/*.cy.{js,jsx,ts,tsx} which files are specs
defaultCommandTimeout 4000 how long queries and assertions retry (ms)
viewportWidth / viewportHeight 1000 / 660 the size of the application frame
retries 0 how often a failed test is retried (see below)
video false record a video of each spec during cypress run
screenshotOnRunFailure true take a screenshot when a test fails in cypress run

You can override any option for a single run without editing the file:

npx cypress run --config baseUrl=https://staging.example.com

or for one spec or test, by passing a config object as the second argument of describe or it, for example it('loads a big report', { defaultCommandTimeout: 10000 }, () => { ... }).

setupNodeEvents and cy.task#

Your spec runs in the browser, so it cannot read files, query a database or print to the terminal. setupNodeEvents runs in the Node.js process, and cy.task() calls into it. The log task above prints to the terminal running cypress run, which is useful in CI where nobody is watching the browser:

cy.task('log', `logged in as ${Cypress.env('username')}`)

A task must return a value or a promise, or null when there is nothing to return; returning undefined fails the command. Plugins (code coverage, file downloads, Cucumber preprocessors) hook in here too.

A test needs to reset a database row before it runs. Where does the code that talks to the database belong?

Specs and support files are bundled and run in the browser, where Node.js modules such as database drivers do not work. Tasks run in the Node.js process, and cy.task() is the bridge. (An API endpoint called with cy.request is the other common option.)

Environment variables#

Cypress has its own set of environment variables, read in tests with Cypress.env('name'). They can come from four places; when the same name is set in several, the later ones in this list win:

  1. the env object in cypress.config.js,
  2. a cypress.env.json file next to the config,
  3. operating system variables prefixed with CYPRESS_ (the prefix is stripped: CYPRESS_username becomes username),
  4. the --env flag: npx cypress run --env username=tomsmith,password=....

Chapter 5 read the login credentials from cypress.env.json. In CI there is no such file; instead you set CYPRESS_username and CYPRESS_password from the CI system's secret store, and the specs do not change. We checked the order with a run that had username in cypress.env.json and in CYPRESS_username, and password in the file and in --env: the shell variable and the flag both won.

CYPRESS_ variables whose names match a configuration option set that option instead. CYPRESS_BASE_URL=https://staging.example.com npx cypress run changes baseUrl for the run, which is the simplest way to aim one suite at localhost, staging and production.

cypress.env.json on a developer's laptop sets password to a local value. In CI the job sets CYPRESS_password from a secret. Which value does Cypress.env('password') return in CI if the file was accidentally committed?

OS-level CYPRESS_ variables take precedence over cypress.env.json, and --env takes precedence over both. The committed secret is still a leak, though: add the file to .gitignore.

A note on Cypress 16#

Everything in Cypress.env() is sent to the browser, so any script on the page under test could read it. Cypress 15.10 deprecated Cypress.env() and Cypress 16 removed it: secrets are read with the asynchronous cy.env(['password']), and values that are not secret and need synchronous access use Cypress.expose(). This course uses Cypress.env() because it pins Cypress 14.2.0 to match the version TestingBot runs (chapter 8) and because the TestingBot environment variables guide uses it. If you upgrade to Cypress 16 locally, follow the migration guide in the Cypress documentation.

Test retries#

Even a careful suite meets a flaky test now and then: a slow CI machine, a third-party script, a real race in the app. retries reruns a failed test before declaring it failed:

retries: { runMode: 2, openMode: 0 },
  • runMode applies to cypress run (CI): up to two extra attempts.
  • openMode applies to cypress open: none, because while you are writing a test you want to see it fail.

A number instead of the object (retries: 2) applies to both. A single test can override it: it('uploads a file', { retries: 3 }, () => { ... }).

When a retry happens, the output shows it, for example (Attempt 1 of 3) asserts that something is gone, and the test is reported as passed if a later attempt passes. Retries do not rerun before hooks, but beforeEach runs again for every attempt.

Treat every retry as a bug report. Chapter 9 shows a test that passed on its second attempt and turned out to have found a real bug in the application; with retries on and nobody reading the output, it would have stayed hidden.

Why does the course configure openMode: 0 rather than retrying in interactive mode too?

Retries are a safety net for CI, where an occasional infrastructure hiccup should not block a merge. In interactive mode a silent retry makes a flaky test look healthy at exactly the moment you could investigate it.