Within Cypress, you can retrieve the current page's URL using the cy.url() command. This command fetches the URL of the currently tested page and returns a Promise, which can be utilized for subsequent chained operations or assertions. Here's an example of using cy.url():
javascriptdescribe('URL Test', () => { it('should check the current URL', () => { // Navigate to a website cy.visit('https://example.com'); // Retrieve the current URL and verify it contains a specific path cy.url().should('include', '/somePath'); // You can also use `then()` to retrieve the URL value and perform more complex operations cy.url().then((currentUrl) => { // You can use the `currentUrl` variable to perform actions // For example, log the current URL console.log('The current URL is:', currentUrl); }); }); });
In the above example, the cy.visit command navigates to the specified website, and then we retrieve the current page's URL using cy.url(). Using .should('include', '/somePath') ensures that the retrieved URL contains a specific path segment. If you need to perform more complex logic on the retrieved URL, you can use the .then() method to handle the currentUrl variable within a callback function. In this manner, Cypress provides a simple yet powerful way to interact with web pages during testing and can be easily combined with other Cypress commands to create complex test cases.