Before Spec API

The before:spec event fires before a spec file is run. When running cypress via cypress open, the event will fire when the browser launches.

Syntax

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  // setupNodeEvents can be defined in either
  // the e2e or component configuration
  e2e: {
    setupNodeEvents(on, config) {
      on('before:spec', (spec) => {
        /* ... */
      })
    }
  }
})
import { defineConfig } from 'cypress'

export default defineConfig({
  // setupNodeEvents can be defined in either
  // the e2e or component configuration
  e2e: {
    setupNodeEvents(on, config) {
      on('before:spec', (spec) => {
        /* ... */
      })
    }
  }
})
// cypress/plugins/index.js

module.exports = (on, config) => {
  on('before:spec', (spec) => {
    /* ... */
  })
}

spec (Object)

Details of the spec file, including the following properties:

PropertyDescription
nameThe base name of the spec file (e.g. login.cy.js)
relativeThe path to the spec file, relative to the project root (e.g. cypress/e2e/login.cy.js)
absoluteThe absolute path to the spec file (e.g. /Users/janelane/my-app/cypress/e2e/login.cy.js)

Usage

You can return a promise from the before:spec event handler and it will be awaited before Cypress proceeds running the spec.

Log the relative spec path to stdout before the spec is run

module.exports = (on, config) => {
  on('before:spec', (spec) => {
    // spec will look something like this:
    // {
    //   name: 'login.cy.js',
    //   relative: 'cypress/e2e/login.cy.js',
    //   absolute: '/Users/janelane/app/cypress/e2e/login.cy.js',
    // }

    console.log('Running', spec.relative)
  })
}

See also