When using Cypress for frontend automated testing, you can leverage its rich API to monitor network requests. Cypress offers multiple approaches to view API request history and request logs.
-
Using
cy.intercept()to Capture and View Requests: Cypress enables you to intercept network requests via thecy.intercept()method. This allows you to capture any HTTP requests sent by the application and inspect detailed information about both requests and responses.For example, to intercept GET requests targeting the
/api/usersendpoint, you can implement:javascript// Configure the interceptor before the test case cy.intercept('GET', '/api/users').as('getUsers'); // Initiate the request // ... // Wait for the request to complete and retrieve details cy.wait('@getUsers').then((interception) => { // Inspect request details console.log(interception.request); // Inspect response details console.log(interception.response); });In this scenario, all GET requests sent to
/api/usersare intercepted and can be referenced in tests using the@getUsersalias. -
Viewing Request Logs in the Cypress Test Runner: When executing tests within the Cypress interactive test runner, each request intercepted by
cy.intercept()appears in the left-side command log. Clicking on these log entries expands the details, including the request URL, method, request headers, request body, response status code, response headers, and response body. -
Outputting Logs to the Console: Within your test code, you can utilize
console.log()or other logging methods to print request and response information to the browser's console. This is especially valuable for debugging test scenarios.
Note that the cy.intercept() method not only facilitates viewing requests and responses but also allows you to simulate responses or alter request behavior during tests, making it a versatile tool.
By employing these techniques, you can effectively monitor and manage API request history and request logs in Cypress. This capability is instrumental for validating application network activity and troubleshooting tests.