Search code examples
node.jsnpmcypresspackage.jsoncypress-configuration

Setting baseUrl in npm script doesn't change it (Cypress)


I want to be able to run my Cypress scripts on any URL by modifying the value of baseUrl but the command doesn't change it.

"cypress open --env version=development --config baseUrl=https://google.com"

I have tried env variable too but that also doesn't work:

"cypress:open:dev": "cypress open --env version=development,baseUrl=https://google.com"

Config file:

export default defineConfig({
  e2e: {
    async setupNodeEvents(on, config) {
      const version = config.env.version || 'development'
      const configFile = await import(path.join(
        config.projectRoot,
        'cypress/config',
        `${version}.json`
      ));
      const credentialsFile = await import(path.join(
        config.projectRoot,
        'cypress/config',
        'credentials.json'
      ));
      config = {
        ...config,                    // take config defined in this file
        ...configFile                 // merge/override from the external file
      }
      config.env = {
        ...config.env,                // 2nd level merge
        ...credentialsFile[version]   // from git-ignored file 
      }
      config.baseUrl = configFile.baseUrl
      return config
    },
    reporter: 'mochawesome'
  },
});

development.json:

{
    "env": {
        "baseUrl": "https://test.com",
    }
}

Solution

  • Here is the solution that provides what I was looking for:

    The command, URL is optional, if not provided it uses the hard-coded value in development.json:

    "cypress:open:dev": "CYPRESS_BASE_URL=$URL cypress open --env version=development"
    

    The only line I needed to change in my config was the following:

    config.baseUrl = config.baseUrl || configFile.env.baseUrl
    

    All my tests were using the following:

     cy.visit(Cypress.env('baseUrl'))
    

    So I needed to change to:

     cy.visit('')
    

    With this solution, I can run the script without any argument and it will use default baseUrl, or I can run URL="https://google.com/ npm run cypress:open:dev and the baseUrl will change