Correct Environment Switching in Cypress
Sooner or later, you may have to run your test in several environments simultaneously. And Cypress allows you to do this very efficiently. Let’s take a closer look at the details.
The Use of baseUrl
First, let’s take a look at the special .visit() command. You can use it to open a web browser window at a specific location. But it also allows you to take the baseUrl attribute from the cypress.json file. All that said, if baseUrl is configured to source http://localhost:3000/, all links can be written the following way:
cy.visit(‘/dashboard’)
And as a result, the link will look like http://localhost:3000/dashboard. By the way, the baseUrl attribute is also used in commands like .request() and .intercept(). This will be more correct than using the variable env. For example, the tester doesn’t need to deal with the process of changing the names of everything, if you think about renaming the env variable localUrl.
Rewriting Cypress.json
The easiest way to perform the switch is to rewrite the cypress.jon file and install baseUrl to a different value whenever the user needs to switch the environment. This is a very complicated and time-consuming process if switching needs to be done more often.
Also, this is not the right way if the tester uses so-called version control and wants to run tests in CI. He’ll have to commit every time he tests in a different (new) environment, and the git story becomes a big mess.
Pointing to Other Configuration Files
Instead of applying cypress.json, you can easily configure cypress to a different test file. For example, you have a production.json file where baseUrl is specified as a production server. To start cypress using this file, you can do the following steps:
npx cypress open –config-file production.json
Note, that this command also functions for the Cypress run command.
Using the Modular API
With the modular API, it is possible to reproduce tests quite flexibly. With it, the user will use his default script instead of the npx cypress run command. In this situation, you will create something like node cypress-run.js in the terminal, and the output will be as follows:
cypress/cypress-run.js
const cypress = require(‘cypress’)
cypress.run()