Node Events Overview
Use Node event hooks 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 you can use to change the behavior of Cypress or to expose plugins for others to consume.
setupNodeEventsruns in the Node process 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. The function can return a synchronous
value or can also return a Promise, which Cypress awaits until it resolves.
Because Cypress awaits the Promise, setupNodeEvents can perform asynchronous
actions such as reading files in from the filesystem.
If you return or resolve with an object, Cypress then merges this object
into the config, overwriting configuration or environment variables.
- cypress.config.js
- cypress.config.ts
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
},
},
})
import { defineConfig } from 'cypress'
export default 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 use to register listeners on various events
that Cypress exposes.
Registering to listen on an event looks like this:
- cypress.config.js
- cypress.config.ts
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
})
},
},
})
import { defineConfig } from 'cypress'
export default 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.
| Event | Description |
|---|---|
after:run | Occurs after the run is finished. |
after:screenshot | Occurs after a screenshot is taken. |
after:spec | Occurs after a spec is finished running. |
before:browser:launch | Occurs immediately before launching a browser. |
before:run | Occurs before the run starts. |
before:spec | Occurs when a spec is about to be run. |
file:preprocessor | Occurs when a spec or spec-related file needs to be transpiled for the browser. |
task | Occurs 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 Cypress passes into the browser for your project.
Some plugins may use or require these values, so they can take certain actions based on the configuration. If you modify these values programmatically, Cypress uses the new values.
The config object also includes the following extra values that are not part
of the standard configuration. These values are read only, and you can't
modify them 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. You can use the version to handle breaking changes.
To modify configuration, see the Configuration API.
Use Cases
Configuration
Hooking into node events programmatically alters the resolved configuration and
environment variables that come from the
Cypress configuration file,
cypress.env.json,
the command line, or system environment
variables.
Alter the configuration to:
- Use multiple environments with their own configurations
- Swap out environment variables based on an environment
- Read in configuration files using the built in
fslib - 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
Use the file:preprocessor event to customize how Cypress transpiles your test
code and sends it to the browser. By default, Cypress handles ES2015+ and
TypeScript, 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 Vite 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 Cypress runs a single
spec, 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. Deleting the video 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 you keep videos for failing tests for debugging purposes).
Check out the Before Spec API doc and After Spec API doc which describe how to use these events.
Browser Launching
Use the before:browser:launch event 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
Standard, Chrome-branded browsers (for example, regular Google Chrome) version
137 and above can no longer load extensions through the before:browser:launch
event. The change is because Chrome removed support for the --load-extension command
line flag that Cypress relied on to load extensions.
To continue loading extensions, run your tests in Chrome for Testing or Chromium, which still support extension loading.
Check out our Browser Launch API docs which describe how to use this event.
Screenshot handling
Cypress calls the after:screenshot event after it takes a screenshot and saves
it 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 task event works in conjunction with the
cy.task() command. The task event runs 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
Cypress invokes the
setupNodeEvents function
when it opens a project.
Cypress does this by spawning an independent child_process which then
requires the Cypress configuration file.
This child process is similar to the way Visual Studio Code or Atom works.
Cypress runs the configuration code using the Node version that launched Cypress.
Because the configuration code runs in Node, you debug it with a Node debugger rather than the browser's Developer Tools. See Debug setupNodeEvents and tasks with a Node debugger.
npm modules
When Cypress executes the
setupNodeEvents function
it executes with
process.cwd() set to your project's path. Additionally - you can
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:
- cypress.config.js
- cypress.config.ts
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
},
},
})
import { defineConfig } from 'cypress'
export default 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
Cypress loads the Cypress configuration file in its own child process, isolated from the context that Cypress itself runs in. That isolation means you cannot accidentally modify or change Cypress's own execution in any way.
If your setupNodeEvents
function has an
uncaught exception, an unhandled rejection from a promise, or a syntax error -
Cypress automatically catches those and displays them to you inside of the
console and even in Cypress itself.
Errors in your setupNodeEvents function do 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 take effect immediately. Cypress reads the file in and executes the exported function again.
Because Cypress watches the file, you can iterate on plugin code while Cypress is already running.
Each change to a watched file starts a new config process. A debugger attached to the old process doesn't follow it on its own, but the VS Code JavaScript Debug Terminal reattaches for you, as described in Debug the Cypress config process in VS Code.
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.
⚠️ 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.
- cypress.config.js
- cypress.config.ts
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)
)
},
})
},
},
})
import { defineConfig } from 'cypress'
export default 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.