In Cypress, you can access the baseURL value in multiple ways. The baseURL is specified in Cypress's configuration file and typically represents the root URL of the application, allowing you to use relative paths in tests without explicitly defining the full URL. Here are several methods to access the baseURL:
-
Using Relative Paths with
cy.visit(): When using a relative path withcy.visit(), Cypress automatically prepends thebaseURLto the path. For example, if you setbaseURLtohttps://example.com, you can use it as follows:javascriptcy.visit('/page'); // Actual URL accessed will be https://example.com/page -
Accessing via Cypress Configuration Commands: You can use the
Cypress.config()function to access the current configuration, includingbaseURL. For example:javascriptconst baseURL = Cypress.config('baseUrl'); console.log(baseURL); // Outputs the baseURL set in the configuration file -
Dynamically Setting in Tests: If you need to dynamically change the
baseURLduring test execution, you can use theCypress.config()method:javascriptCypress.config('baseUrl', 'https://newexample.com'); // Subsequent `cy.visit('/')` will access https://newexample.com/ -
Using Environment Variables: You can also override the
baseURLin the configuration file by setting environment variables. When running Cypress from the command line, use theCYPRESS_BASE_URLenvironment variable:shellCYPRESS_BASE_URL=https://anotherexample.com npx cypress openIn tests, the
baseURLwill be set tohttps://anotherexample.com.
As a practical example, suppose you need to access a login page in tests with the path /login. If the baseURL is configured as https://example.com, you can write the following Cypress test code:
javascriptdescribe('Login Page Test', () => { it('should visit the login page', () => { // Directly using relative path; Cypress automatically prepends the baseURL cy.visit('/login'); // Perform assertions on the login page... }); it('should dynamically get the baseURL and construct the full URL', () => { // Retrieve the baseURL const baseURL = Cypress.config('baseUrl'); // Construct the full URL using the retrieved baseURL and visit cy.visit(`${baseURL}/login`); // Perform assertions on the login page... }); });
In the first test case, I directly use cy.visit('/login'), and Cypress automatically prepends the baseURL. In the second test case, I first retrieve the baseURL value and then manually construct the full URL to access the login page. Both approaches can be chosen based on the test requirements.