Modify API Response | Bondar Academy
Course: Cypress UI Testing with JavaScript
Module: Working with APIs
Instructor: Artem Bondar
Lesson Summary
In this lesson, we explore how to intercept and modify API responses using Cypress, which is particularly useful for testing edge cases in applications. Why Intercept API Responses? When testing scenarios like a likes counter that needs to handle large values (e.g., 10 million likes), manually updating the database can be cumbersome. Instead, mocking data allows for consistent reproduction of scenarios without risking database integrity. Steps to Modify API Responses in Cypress Set Up Interception: Create a new test and intercept the API request. Use Callback Functions: Provide a callback function to handle the request. Continue the Request: Allow the request to go through using the continue method. Modify the Response: Catch the response and modify specific properties, such as the favorite count . Send the Modified Response: Use res.send to return the modified response to the application. Example Code Snippet cy.intercept('GET', '/api/articles', (req) => { req.continue((res) => { res.body.articles[0].favorite_count = 9999999; // Modify the favorite count res.send(res.body); // Send the modified response }); }); Validation After modifying the response, validate that the application displays the expected values using assertions, such as checking the text of the likes counter. In summary, intercepting and modifying API responses in Cypress allows for efficient testing of edge cases without altering the underlying database, ensuring reliable test automation.