Skip to main content

Overview

Node event hooks enable you to tap into, modify, or extend the internal behavior of Cypress.

Normally, as a user, all of your test code, your application, and Cypress commands are executed in the browser. But Cypress is also a Node process that can be used to change the behavior of Cypress or to expose plugins for others to consume.

setupNodeEvents enables you to tap into the Node process running outside of the browser.

Node event hooks are a "seam" for you to write your own custom code that executes during particular stages of the Cypress lifecycle.

setupNodeEvents

The setupNodeEvents function receives 2 arguments: on and config. It can return a synchronous value or can also return a Promise, which will be awaited until it resolves. This enables you to perform asynchronous actions such as reading files in from the filesystem.

If you return or resolve with an object, Cypress will then merge this object into the config which enables you to overwrite configuration or environment variables.

const { defineConfig } = require('cypress')

module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
// configure plugins here
},
},
})

on

on is a function that you will use to register listeners on various events that Cypress exposes.

Registering to listen on an event looks like this:

const { defineConfig } = require('cypress')

module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
on('<event>', (arg1, arg2) => {
// plugin stuff here
})
},
},
})

List of events

Each event documents its own argument signature.

EventDescription
after:runOccurs after the run is finished.
after:screenshotOccurs after a screenshot is taken.
after:specOccurs after a spec is finished running.
before:browser:launchOccurs immediately before launching a browser.
before:runOccurs before the run starts.
before:specOccurs when a spec is about to be run.
file:preprocessorOccurs when a spec or spec-related file needs to be transpiled for the browser.
taskOccurs in conjunction with the cy.task command.

config

config is the resolved Cypress configuration of the opened project.

This configuration contains all of the values that get passed into the browser for your project.

Some plugins may utilize or require these values, so they can take certain actions based on the configuration. If these values are programmatically modified, Cypress will use the new values.

caution

The config object also includes the following extra values that are not part of the standard configuration. These values are read only and cannot be modified from the plugins file.

  • configFile: The absolute path to the Cypress configuration file. See the --config-file and configFile docs for more information on this value.
  • projectRoot: The absolute path to the root of the project (e.g. /Users/me/dev/my-project)
  • version: The version number of Cypress. This can be used to handle breaking changes.

Please check out our API docs for modifying configuration here.

Use Cases

Configuration

Hooking into node events allows you to programmatically alter the resolved configuration and environment variables that come from the Cypress configuration file, cypress.env.json, the command line, or system environment variables.

This enables you to do things like:

  • Use multiple environments with their own configurations
  • Swap out environment variables based on an environment
  • Read in configuration files using the built in fs lib
  • Change the list of browsers used for testing
  • Write your configuration in yml

Check out our Configuration API docs which describe how to use this event.

Preprocessors

The event file:preprocessor is used to customize how your test code is transpiled and sent to the browser. By default, Cypress handles ES2015+, TypeScript, and CoffeeScript, using webpack to package it for the browser.

You can use the file:preprocessor event to do things like:

  • Add the latest ES* support.
  • Write your test code in ClojureScript.
  • Customize the Babel settings to add your own plugins.
  • Customize the options for compiling TypeScript.
  • Swap out webpack for Browserify or anything else.

Check out our File Preprocessor API docs which describe how to use this event.

Run Lifecycle

The events before:run and after:run occur before and after a run, respectively.

You can use before:run to do things like:

  • Set up reporting on a run
  • Start a timer for the run to time how long it takes

You can use after:run to do things like:

  • Finish up reporting on a run set up in before:run
  • Stop the timer for the run set up in before:run

Spec Lifecycle

The events before:spec and after:spec run before and after a single spec is run, respectively.

You can use before:spec to do things like:

  • Set up reporting on a spec running
  • Start a timer for the spec to time how long it takes

You can use after:spec to do things like:

  • Finish up reporting set up in before:spec
  • Stop the timer for the spec set up in before:spec
  • Delete the video recorded for the spec. This prevents it from taking time and computing resources for compressing and uploading the video. You can do this conditionally based on the results of the spec, such as if it passes (so videos for failing tests are preserved for debugging purposes).

Check out the Before Spec API doc and After Spec API doc which describe how to use these events.

Browser Launching

The event before:browser:launch can be used to modify the launch arguments for each particular browser.

You can use the before:browser:launch event to do things like:

  • Load a Chrome extension
  • Enable or disable experimental chrome features
  • Control which Chrome components are loaded

Check out our Browser Launch API docs which describe how to use this event.

Screenshot handling

The event after:screenshot is called after a screenshot is taken and saved to disk.

You can use the after:screenshot event to do things like:

  • Save details about the screenshot
  • Rename the screenshot
  • Manipulate the screenshot image by resizing or cropping it

Check out our After Screenshot API docs which describe how to use this event.

cy.task

The event task is used in conjunction with the cy.task() command. It allows you to write arbitrary code in Node to accomplish tasks that aren't possible in the browser.

You can use the task event to do things like:

  • Manipulating a database (seeding, reading, writing, etc.)
  • Storing state in Node that you want persisted (since the driver is fully refreshed on visits)
  • Performing parallel tasks (like making multiple http requests outside of Cypress)
  • Running an external process (like spinning up a Webdriver instance of another browser like Safari or puppeteer)

Execution context

The setupNodeEvents function (or deprecated [plugins file][legacypluginsfile] function) is invoked when Cypress opens a project.

Cypress does this by spawning an independent child_process which then requires the Cypress configuration file. This is similar to the way Visual Studio Code or Atom works.

This code will be executed using the the Node version that launched Cypress.

npm modules

When Cypress executes the setupNodeEvents function (or deprecated [plugins file][legacypluginsfile] function) it will execute with process.cwd() set to your project's path. Additionally - you will be able to require any node module you have installed, including local files inside your project.

For example, if your package.json looked like this:

{
"name": "My Project",
"dependencies": {
"debug": "x.x.x"
},
"devDependencies": {
"lodash": "x.x.x"
}
}

Then you could do any of the following in your setupNodeEvents function:

const { defineConfig } = require('cypress')

module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
const _ = require('lodash') // yup, dev dependencies
const path = require('path') // yup, core node library
const debug = require('debug') // yup, dependencies
const User = require('./lib/models/user') // yup, relative local modules

console.log(__dirname) // /Users/janelane/Dev/my-project
console.log(process.cwd()) // /Users/janelane/Dev/my-project
},
},
})

Error handling

The Cypress configuration file is loaded in its own child process so it is isolated away from the context that Cypress itself runs in. That means you cannot accidentally modify or change Cypress's own execution in any way.

If your setupNodeEvents function (or deprecated [plugins file][legacypluginsfile] function) has an uncaught exception, an unhandled rejection from a promise, or a syntax error - Cypress will automatically catch those and display them to you inside of the console and even in Cypress itself.

Errors in your setupNodeEvents function will not crash Cypress.

File changes

Normally when writing code in Node, you typically have to restart the process after changing any files.

Cypress automatically watches your Cypress configuration file and any changes made will take effect immediately. We will read the file in and execute the exported function again.

This enables you to iterate on plugin code even with Cypress already running.

Real World Example

The Real World App (RWA) uses tasks to re-seed its database, and to filter/find test data for various testing scenarios.

caution

⚠️ This code is part of the setupNodeEvents function and thus executes in the Node environment. You cannot call Cypress or cy commands in this function, but you do have the direct access to the file system and the rest of the operating system.

const { defineConfig } = require('cypress')

module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
on('task', {
async 'db:seed'() {
// seed database with test data
const { data } = await axios.post(`${testDataApiEndpoint}/seed`)
return data
},

// fetch test data from a database (MySQL, PostgreSQL, etc...)
'filter:database'(queryPayload) {
return queryDatabase(queryPayload, (data, attrs) =>
_.filter(data.results, attrs)
)
},
'find:database'(queryPayload) {
return queryDatabase(queryPayload, (data, attrs) =>
_.find(data.results, attrs)
)
},
})
},
},
})

Check out the Real World App test suites to see these tasks in action.