乐闻世界logo
搜索文章和话题

How to access the value of baseURL in Cypress

1个答案

1

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:

  1. Using Relative Paths with cy.visit(): When using a relative path with cy.visit(), Cypress automatically prepends the baseURL to the path. For example, if you set baseURL to https://example.com, you can use it as follows:

    javascript
    cy.visit('/page'); // Actual URL accessed will be https://example.com/page
  2. Accessing via Cypress Configuration Commands: You can use the Cypress.config() function to access the current configuration, including baseURL. For example:

    javascript
    const baseURL = Cypress.config('baseUrl'); console.log(baseURL); // Outputs the baseURL set in the configuration file
  3. Dynamically Setting in Tests: If you need to dynamically change the baseURL during test execution, you can use the Cypress.config() method:

    javascript
    Cypress.config('baseUrl', 'https://newexample.com'); // Subsequent `cy.visit('/')` will access https://newexample.com/
  4. Using Environment Variables: You can also override the baseURL in the configuration file by setting environment variables. When running Cypress from the command line, use the CYPRESS_BASE_URL environment variable:

    shell
    CYPRESS_BASE_URL=https://anotherexample.com npx cypress open

    In tests, the baseURL will be set to https://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:

javascript
describe('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.

2024年6月29日 12:07 回复

你的答案