Cypress specPattern and excludeSpecPattern

Profile picture for user arilio666

Spec Pattern:

  • Cypress, by default, looks for spec files in our project, which is anywhere with an extension of .cy.js, .cy.jsx, .cy.ts, or .cy.tsx.
  • Instead, it is a glob pattern string of spec files to load.
  • This can be changed for component tests with custom spec pattern values.
  • We can make cypress look for spec files with those extensions but note that this works only when it is in the src folder or any of its subfolders.
{
 component: {
   specPattern: 'src/path/*.cy.{js,jsx,ts,tsx}'
 }
}
  • So this will make cypress run specs from the path with the provided extensions.
  • Also, be cautious that any files found matching e2e.specpattern during this will be automatically excluded.

Exclude Spec Pattern:

  • It is the exact opposite of specPattern, a glob pattern string used to ignore spec files that would otherwise be shown in our list of specs.
  • The pattern is automatically added to specexcludepattern, does not need to be specified, and cannot be overridden.
  • Let us assume that there is a requirement where we need to exclude a test file.
  • We want to exclude all.cy.js from running when the cypress run is executed.

In the /cypress/plugins/index.js, we will have to merge the result with the new value.
Return legacy config if not adding new value.

 setupNodeEvents(on, config) {
     const legacyConfig = require('./cypress/plugins/index.js')(on, config);
     if (config.isTextTerminal) {
        // skip the all.cy.js spec in "cypress run" mode
        return {
          ...legacyConfig,
          excludeSpecPattern: ['cypress/e2e/all.cy.js'],
        }
     }
     return legacyConfig;
   },
 },
 
  • With this method, we can effectively skip a test file.