Search code examples
angularcypressconfigcypress-configuration

setting up cypress for different env when I have different baseUrl and apiUrl on all of them


so I've been setting up my tests on localhost, but now I want to set them up to run on several different environments, but on all of them I have a separate baseUrl and apiUrl. dev has: http://base.url.com and api: http://base.url.com/api prod has: https://prod.url.com and api: https://prod-api.url.com/v1

I've read the documentation and some posts here(although a lot of them are from before cypress v10), but I can't decide what would be the best approach. I'm leaning towards creating different config files(cypress-dev.config.ts, cypress-prod.config.ts etc.), each for a different environment like so:

e2e: { 
  baseUrl: 'http://base.url.com', 
  env: { 
    apiURl: '..'  
}}

creating new npm scripts where I set cypress to use the correct config file when running on a particular environment.

I've considered using one config file, but I'm having trouble figuring out how exactly to do it.

e2e: {    env: { 
    development: { 
      baseUrl:'baseURlDev',
      apiURl: 'apiUrlDev'
    },
    production: {
      baseUrl:'baseURlProd',
      apiURl: 'apiUrlProd'
    },
    staging: {
      baseUrl:'baseURlStag'
      apiURl: 'apiUrlStag'   } 
    }}

and how to use this is my cypress code. Cypress.env('type-of-environment.baseUrl')?? I'm not clear on this.

Or maybe there's third neat way of doing this that I haven't considered yet?


Solution

  • When Cypress v10 changed the configuration from cypress.json to cypress.config.js, one of the benefits was to allow javascript to be used in the config.

    This means fiddly stuff that used to require external packages (like dotenv for this kind of thing) are no longer needed.

    This is how I would implement your type-of-environment

    cypress.config.js

    const { defineConfig } = require("cypress");
    
    module.exports = defineConfig({
      e2e: {
        setupNodeEvents(on, config) {
          const envName = config.env['type-of-environment'] || 'development'
          const envType = config.env[envName] 
          config.baseUrl = envType.baseUrl;
          config.env.apiUrl = envType.apiUrl;
          return config
        },
        env: { 
          development: { 
            baseUrl:'http://baseURlDev',
            apiUrl: 'http://apiUrlDev'
          },
          production: {
            baseUrl:'http://baseURlProd',
            apiUrl: 'http://apiUrlProd'
          },
          staging: {
            baseUrl:'http://baseURlStag',
            apiUrl: 'http://apiUrlStag'   
          },
        }
      },
    })
    

    package.json

    {
      ...
      "scripts": {
        "cy:open": "cypress open",         // defaults to development
        "cy:prod": "cypress open --env type-of-environment=prod"
      }
    }