How to change Cypress baseURL in test?
By Hamid Akhtar, Community Contributor - May 2, 2023
Cypress is a popular end-to-end testing framework known for its developer-friendly approach. It provides an efficient and reliable way to write tests with excellent documentation and APIs. One essential aspect of working with Cypress is understanding how to configure the baseURL.
- What is baseURL in Cypress?
- Reasons to change the base URL in Cypress tests
- Get Started with Cypress change baseURL in test
- Setting the base URL in Cypress test configuration
- Examples of changing the base URL in Cypress tests
- Best Practices for using different base URLs in Cypress tests
- Example for adding baseURL while running on BrowserStack
What is baseURL in Cypress?
Cypress automation enables you to specify a baseUrl when configuring your test suite. This baseURL acts as the root URL for each visit command you execute in the test suite. As a best practice, Cypress suggests using the baseUrl setting.
- The baseUrl is a critical configuration setting that specifies the root URL of your application.
- It serves as the base for all cy.visit() calls in your tests.
- Defining a baseUrl in your Cypress configuration file enables you to use relative URLs in your tests, making them more readable and maintainable.
Reasons to change the base URL in Cypress tests
- While writing tests, you prefer to run them first in a local setting. There are just a few reasons for this. You have to add the data-cy, check it, and run the tests.
- Prior to performing tests in a test/staging environment, you must ensure that local/development environment conditions are suitable for testing.
- You might also need to configure the CI pipeline so that it can execute in various environments. In such cases, the baseUrl will be distinct between the two environments. However, in cypress.json, baseUrl can only be configured once.
- The Cypress test runner will open localhost or baseURL on a random port when it first launches. It will switch to the requested URL upon your first request. Without a global baseUrl provided, starting tests will result in an unnecessary reload.
- Using a baseURL has the added benefit of allowing Cypress to test the url when the test begins and notify you right away if the application isn’t accessible for testing.
- Once the baseURL has been established for the test suite, any subsequent visits to the application under test can be made via relative links. As the baseUrl can be changed during startup configuration, you can target various environments without having to make a lot of environment-specific link settings.
- The baseURL is used to determine the relative address in the event that your application returns a relative redirect that results in the opening of a new URL. If the baseUrl is present, then this is true. The last page visited is utilized if it is not set.
- Between testing, Cypress clears localStorage and cookies, but not session storage. You would need to clear it as part of your setup if your application uses session storage and you need to clear it for a test. When the window is opened. The baseUrl, which serves as the origin of the current window, is affected by sessionStorage.clear().
Get Started with Cypress change baseURL in test
From the project root, you can now access Cypress in one of the following ways:
npx usage
Keep in mind that npx can be installed independently or as part of npm > v5.2.
npx cypress open
or by using yarn
yarn run cypress open
The long route that follows the entire path:
./node_modules/.bin/cypress open
Alternatively, you can use the npm bin shortcut
$(npm bin)/cypress open
The Cypress Launchpad will open in a little while.
Adding npm Scripts
While there is nothing wrong with writing the complete path to the Cypress executable each time, adding Cypress commands to the scripts field in your package.json is considerably simpler and more understandable.
{ "scripts": { "cypress:open": "cypress open" } }
You may now run the command from the project root as shown here:
npm run cypress:open
Cypress will open up for you right away.
CLI tools
You may also access a large number of other CLI tools by installing Cypress via npm. Plus, you may import Cypress, a properly baked JavaScript library, into your Node scripts.
The Launchpad will scaffold out a set of configuration files suited for your selected testing type, and you will be given a list of the modifications to examine.
Setting the base URL in Cypress test configuration
When using Cypress, the base URL can be given in the configuration file and used dynamically to load the URL.
To call the set URL dynamically, URLs are set here and invoked. Add the following line inside env to cypress.config.js.
env: { baseUrl: 'https://www.programsbuzz.com/user/login', },
The baseURL is given this name in the spec file:
cy.visit(Cypress.env("baseUrl"))
You can do this to take a more dynamic approach:
npx cypress run --config baseUrl=https://example.com/
Otherwise, in the package .JSON, you may set a script similar to the following:
"scripts": { "test": "cypress run", "test:staging": "cypress run --config baseUrl=https://staging-example.com/", "test:prod": "cypress run --config baseUrl=https://prod-example.com/" }
Then:
npm run test:staging npm run test:prod
Examples of changing the base URL in Cypress tests
A wise move is to define a base URL globally in your Cypress configuration file before testing your applications with Cypress. This increases test efficiency and makes moving the test suite between various environments—like a development site and a live website—less challenging. Here’s an instance of that:
// cypress.config.js import { defineConfig } from 'cypress' export default defineConfig({ e2e: { baseUrl: 'http://localhost:3000' } })
You can abbreviate the URLs in your tests by setting the base URL in your configuration file
from
cy.visit('http://localhost:3000/index.html')
to
cy.visit('index.html')
It is simpler to change the base URL from one spot when you are ready to switch to the production site. A further advantage is that providing a base URL speeds up Cypress test startup.
Most likely, you’ll want to run your tests in several environments:
cy.visit(Cypress.env('localUrl'))
Let’s first examine the .visit() instruction. This command will start a browser at the specified location. But it also uses the baseUrl attribute from your cypress.json file.
This implies that if your baseUrl is set to http://localhost:3000, you may write your URLs like this:
cy.visit('/dashboard')
and http://localhost:3000/dashboard will be the resolved location. The commands .request() and .intercept() also use the baseUrl attribute. Instead of using an environment variable, do this. You won’t have to bother renaming everything if you decide one day to change the name of your localUrl environment variable.
Best Practices for using different base URLs in Cypress tests
Rewriting your cypress.json file and setting baseUrl to a different value each time you wish to switch environments is the best way to accomplish it. It goes without saying that this is irritating and needs way too much work if you need to switch regularly.
Additionally, this is not the greatest strategy if you want to run your tests in continuous integration and use version control. You must commit each time you wish to test in a different environment, which clogs up your git history.
Pointing to an alternative configuration file
You can direct Cypress to a different file entirely instead of using cypress.json. Assume you have a production.json file with the baseUrl attribute set to the production server. You can perform the following actions to execute Cypress using this file:
npx cypress open --config-file production.json
Naturally, the Cypress run command also functions in this manner.
If you only want to make changes to the baseUrl attribute, you can do so by passing it through the CLI:
npx cypress open --baseUrl http://localhost:3000
Example for adding baseURL while running on BrowserStack
{ "baseUrl":"https://www.browserstack.com/users/sign_up", "fileServerFolder": ".", "testFiles": "**/*.spec.ts", "fixturesFolder": "cypress/fixtures", "integrationFolder": "cypress/integration", "pluginsFile": false, "supportFile": false, "snapshots": true, "trashAssetsBeforeRuns": true, "reporter":"mochawesome", "chromeWebSecurity": false, "pageLoadTimeout": 60000, "reporterOptions":{ "reportDir": "cypress/report/mochawesome-report", "reportFilename": "testReport", "charts":true, "overwrite":false, "html":true, "json":false, "timestamp" : "mm/dd/yyyy_HH:MM:ss" } }
Cypress_local.json
Closing Notes
As indicated in the official Cypress documentation, it is not a good idea to forget to set a baseUrl in the Cypress configuration file. This has a few general advantages for the tool’s usability, like making it possible to identify server problems before conducting any tests. But, the major goal is to prevent a second page reload every time Cypress accesses a URL, which will make Cypress tests run more quickly and without interruption.
You need to test under real user conditions for stable testing, and a real device cloud like BrowserStack for Cypress is a perfect pick for this. You can anticipate problems and address them before your product enters production by having access to various devices.