Using setupNodeEvents with Cypress preset

The setupNodeEvents function in a Cypress configuration file allows you to tap into the internal behavior of Cypress using the on and config arguments.

cypress.config.ts
1import { defineConfig } from 'cypress'; 2 3export default defineConfig({ 4 e2e: { 5 setupNodeEvents(on, config) { 6 // e2e testing node events setup code 7 }, 8 }, 9}); 10

The Cypress preset that Nx provides (@nx/cypress/plugins/cypress-preset) uses setupNodeEvents to start the web server. Thus, if you provide your own function, then you must invoke the setupNodeEvents function that our preset provides.

cypress.config.ts
1import { defineConfig } from 'cypress'; 2import { nxE2EPreset } from '@nx/cypress/plugins/cypress-preset'; 3 4const config = nxE2EPreset(__filename, { 5 cypressDir: 'src', 6 bundler: 'vite', 7 webServerCommands: { 8 default: 'nx run my-project:serve', 9 production: 'nx run my-project:preview', 10 }, 11 ciWebServerCommand: 'nx run my-project:serve-static', 12}); 13 14export default defineConfig({ 15 e2e: { 16 ...config, 17 async setupNodeEvents(on, config) { 18 // This line sets up the web server as provided via `webServerCommands` and `ciWebServerCommand` 19 await config.setupNodeEvents(on, config); 20 21 // Register your listeners here 22 }, 23 }, 24}); 25
Nx 15 and lower use @nrwl/ instead of @nx/
Note on async-await

The setupNodeEvents function from our Cypress preset returns a promise, so make sure to await the result.