When using Cypress for end-to-end testing, you may need to intercept and mock HTTP requests to specific URLs. Cypress provides a powerful command cy.intercept(), which allows you to intercept network requests. When you want to use wildcards to intercept specific URLs, you can achieve this by passing a matching pattern.
Here is a specific example to illustrate how to use wildcards to intercept URLs:
Suppose you are testing an e-commerce website and need to intercept all API calls related to product searches. The URL structure for the search API is as follows:
shellhttps://api.example.com/products/search?q=query term
You can use the wildcard * to match any possible query term. The example code is as follows:
javascriptcy.intercept('GET', 'https://api.example.com/products/search?q=*').as('search');
In this example, the cy.intercept() function intercepts all GET requests starting with https://api.example.com/products/search?q=. The wildcard * matches any possible query term.
After that, you can use the alias search to wait for this intercepted request for validation or assertions in your tests. For example, you can check if you received the correct response code and response body:
javascriptcy.wait('@search').its('response.statusCode').should('eq', 200); cy.wait('@search').its('response.body').should('have.length', 10);
This approach is well-suited for handling dynamic or uncertain URL structures, allowing your tests to be more flexible and reliable.