How run multiple test spec without define absolute path repeatly in Cypress

635 Views Asked by At

Based on the Cypress documentation, we can run multiple test files using this syntax

cypress run --spec "cypress/e2e/examples/actions.cy.js,cypress/e2e/examples/files.cy.js"

My question is when I have to run 4 of 10 test files in the same folder i have to define like this,

cypress run --spec "cypress/e2e/**/test1.cy.js,cypress/e2e/**/test2.cy.js,cypress/e2e/**/test3.cy.js,cypress/e2e/**/test4.cy.js" 

Can we make simplify it, idk is cypress has a feature for defining the spec folder?

So if we can define the folder test spec path like specFolder = cypress/e2e/**/ and I just write script

cypress run --spec "test1.cy.js,test2.cy.js,test3.cy.js,test4.cy.js" 
2

There are 2 best solutions below

1
On

You can run all tests in a specified directory as documented here https://docs.cypress.io/guides/guides/command-line#cypress-run-spec-lt-spec-gt

So try to run all the tests in a directory like so

cypress run --spec "cypress/e2e/**/*
0
On

You can use a a little javascript in cypress.config.js to do it, but instead of --spec option specify the tests in an --env variable.

// cypress.config.js

const { defineConfig } = require("cypress");

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {

      if (config.env.specs) {  // only if specs are specified on CLI

        const specBase = config.specPattern.split('*')[0]  // === "cypress/e2e/"
        // temporary change to specPattern
        config.specPattern = config.env.specs.map(spec=> `${specBase}${spec}`)
      }
      return config
    },
    specPattern: 'cypress/e2e/**/*.cy.{js,jsx,ts,tsx}'
  },
});

Called with script

// package.json

{
  "scripts": {
    "cy:specs": "npx cypress run --env specs=[test1.cy.js,test2.cy.js]"
  }
}

Run output:

specPattern [ 'cypress/e2e/test1.cy.js', 'cypress/e2e/test2.cy.js' ]

=====================================================================================

  (Run Starting)

  ┌─────────────────────────────────────────────────────────────────────────────────┐
  │ Cypress:        12.3.0                                                          │
  │ Browser:        Electron 106 (headless)                                         │
  │ Node Version:   v18.12.1 (C:\Program Files\nodejs\node.exe)                     │
  │ Specs:          2 found (test1.cy.js, test2.cy.js)                              │
  │ Searched:       cypress/e2e/test1.cy.js, cypress/e2e/test2.cy.js                │
  └─────────────────────────────────────────────────────────────────────────────────┘

  Running:  test1.cy.js                                                      (1 of 2)
etc