How to extend cypress.json config to other configuration files?

Viewed 429

In my Cypress framework, I have the following config files at the root level of my project.

  • cypress.json (Contains configs for mochawesome report tool)

  • qa.json (Points at my QA environment).

  • staging.json (Points at my Staging environment).

Here is what my staging.json file looks like:

{
    "extends": "./cypress.json",
    "baseUrl": myStagingUrl,
}

As you can see I am trying to extend cypress.json so that I don't have to duplicate the mochawesome configuration.

Here is what my cypress.json file looks like:

{
  "reporter": "cypress-mochawesome-reporter",
  "reporterOptions": {
    "reportDir": "cypress/reports",
    "charts": true,
    "reportPageTitle": "My Test Suite",
    "embeddedScreenshots": true,
    "inlineAssets": true
  },
  "video": false
}

When I run npx cypress run --config-file staging.json, the tests run but the HTML test report isn't generated.

If I copy & paste the values from cypress.json into staging.json, the HTML report is generated.

So the cypress.json isn't being picked up by the tests at all.

Can someone please tell me how I can extend the cypress.json so its' values are picked up even when I use other config files?

1 Answers

There's a package that does pretty much what you want to do.

cypress-extends

Cypress plugin that adds "extends" support to the configuration file. This allows the config files to remain DRY and avoid duplicating data, but still have multiple files for different scenarios.

// cypress.json
{
  "extends": "./base.json"
}
// base.json
{
  "fixturesFolder": false,
  "supportFile": false,
  "$schema": "https://on.cypress.io/cypress.schema.json"
}

In the docs Extending the Cypress Config File


Cypress v10

With the latest Cypress version, config changes from .json to .js file.

Now you can just import and merge the base.json, but you need to be careful about sub-sections of the comfig

cypress.config.js

const { defineConfig } = require('cypress')
const baseConfig = require('base.json')

module.exports = defineConfig({
  e2e: {
    baseUrl: baseConfig.baseUrl || 'http://localhost:1234'  // example OR 
  }
})

Or maybe this is more general

const { defineConfig } = require('cypress')
const baseConfig = require('base.json')

const e2e = {
  baseUrl: 'http://localhost:1234',
  fixturesFolder: false,
  supportFile: false,
  "$schema": "https://on.cypress.io/cypress.schema.json"
}

module.exports = defineConfig({
  e2e: {
    ...e2e,           // values from above
    ...baseConfig     // add or overwrite from imported file
  }
})

It's more powerful merging in javascript, but also easier to get wrong. Please refer to the Testing Type-Specific Options for a reference to what goes where in the new format.

Related