When working with Cypress for end-to-end testing, maintaining flexibility and scalability in your test setup is important.
One of the key configurations that helps with flexibility is the baseURL setting, which defines the root URL for your tests. Instead of hardcoding URLs in every test file, set or change the baseURL dynamically.
Read this guide to learn more about the baseURL in Cypress, how to use it, and best practices to be followed.
What is baseURL in Cypress?
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.
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.
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.
How to Pass baseUrl through CLI?
Here are the steps to be followed for passing baseURL through CLI:
Step 1: Open Terminal in your Project Directory
Move to the root directory of your Cypress project using the terminal or command prompt.
Step 2: Use the –config Flag to Override baseUrl
Cypress allows overriding configuration options directly through the CLI using the –config flag. To set a custom baseUrl, use the following syntax:
npx cypress run --config baseUrl=https://your-custom-url.com
Step 3: Pass baseURL for Specific Test Files
Target specific spec files while passing the baseUrl. For example:
npx cypress run --spec cypress/e2e/login.cy.js --config baseUrl=https://staging.example.com
Step 4: Combine with Other Config Options
The –config flag accepts a comma-separated list of key-value pairs. This means users can modify multiple configuration values in a single command:
npx cypress run --config baseUrl=https://qa.example.com,defaultCommandTimeout=10000
Step 5: Verify baseUrl in Your Tests
If needed, a user can log or assert the current base URL in the tests using:
cy.log(Cypress.config('baseUrl'));
Read More: How to run specific test in Cypress
Setting the baseURL Dynamically 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
Other Ways to Set Up Base URL in Cypress
Apart from using the CLI, Cypress offers some of the other common methods to set the baseUrl:
1. Using the cypress.config.js or cypress.config.ts File
This is the most standard way to set a base URL, i.e, by defining it directly in your Cypress configuration file.
const { defineConfig } = require('cypress') module.exports = defineConfig({ e2e: { baseUrl: 'https://example.com' } })
2. Using Environment-Specific Config Files
For teams running tests in multiple environments (like dev, staging, or production), create custom configuration files and pass them when running tests.
npx cypress run --config-file cypress.config.staging.js
Inside cypress.config.staging.js: module.exports = { e2e: { baseUrl: 'https://staging.example.com' } }
3. Using Environment Variables
Set the baseUrl using environment variables, which is useful for CI/CD pipelines or dynamic setups. Cypress supports this via the CYPRESS_baseUrl variable:
CYPRESS_baseUrl=https://qa.example.com npx cypress run
4. Using Cypress.config() at Runtime (Less Common)
Although not recommended for global config changes, users can set the base URL inside a test or support file using Cypress.config():
Cypress.config('baseUrl', 'https://dynamic-url.com')
5. Using cypress.env.json in Combination with Custom Logic
You can dynamically set the baseUrl in Cypress based on environment variables by combining a cypress.env.json file with custom logic in cypress.config.js:
{ "env": "staging", "stagingBaseUrl": "https://staging.example.com", "prodBaseUrl": "https://www.example.com" }
Then in your cypress.config.js:
const { defineConfig } = require('cypress') module.exports = defineConfig({ e2e: { baseUrl: process.env.CYPRESS_env === 'staging' ? 'https://staging.example.com' : 'https://www.example.com' } })
Read More: Cypress Custom Commands
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.
How to Make Assertions with baseUrl?
Making assertions with baseUrl in Cypress is helpful when you want to verify that your tests are running against the correct environment or to confirm that dynamic routing and navigation are working as expected.
Example 1: Assert Current baseUrl
The example given below verifies that the correct baseUrl is set in the Cypress configuration:
describe('Base URL Assertion', () => { it('should have the correct baseUrl set', () => { expect(Cypress.config('baseUrl')).to.equal('https://staging.example.com') }) })
Example 2: Use baseUrl in Navigation Assertions
The example shows how to use the configured baseUrl in navigation tests, ensuring the application correctly routes to the expected page relative to the environment-specific base URL.
describe('Navigation Test', () => { it('should navigate to the login page', () => { cy.visit('/login') cy.url().should('eq', `${Cypress.config('baseUrl')}/login`) }) })
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
Conclusion
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.
Useful Resources for Cypress
Understanding Cypress
- Cross Browser Testing with Cypress : Tutorial
- Run Cypress tests in parallel without Dashboard: Tutorial
- Handling Test Failures in Cypress A Comprehensive Guide
- Cypress Test Runner: Tutorial
- Handling Touch and Mouse events using Cypress
- Cypress Automation Tutorial
- CSS Selectors in Cypress
- Performance Testing with Cypress: A detailed Guide
- Cypress Best Practices for Test Automation
- Test React Native Apps with Cypress
- Cypress E2E Angular Testing: Advanced Tutorial
- Cypress Locators : How to find HTML elements
- Maximizing Web Security with Cypress: A Step-by-Step Guide
- Conditional Testing in Cypress: Tutorial
- Cypress Web Testing Framework: Getting Started
- Cypress Disable Test: How to use Skip and Only in Cypress
- What’s new in Cypress 10? How it will change your current testing requirements
Use Cases
- How to Record Cypress Tests? (Detailed Guide)
- How to run your first Visual Test with Cypress
- How to Fill and Submit Forms in Cypress
- How to Automate Localization Testing using Cypress
- How to run Cypress Tests in Chrome and Edge
- How to use Cypress App Actions?
- How to Run Cypress Tests for your Create-React-App Application
- How to Run Cypress Tests in Parallel
- How to handle Click Events in Cypress
- How to Test React using Cypress
- How to Perform Visual Testing for Components in Cypress
- How to run UI tests in Cypress
- How to test redirect with Cypress
- How to Perform Screenshot Testing in Cypress
- How to write Test Case in Cypress: (with testing example)
Tool Comparisons