Intercepting and Modifying API Response | Bondar Academy
Course: Playwright UI Testing with TypeScript
Module: Interacting with APIs
Instructor: Artem Bondar
Lesson Summary
In this lesson, we will learn how to intercept API responses , modify them, and fulfill these responses back to our application. This technique is particularly useful for making partial modifications to API responses without mocking the entire response. Key Steps Covered: Intercept the API Call: We will intercept the articles API call and modify the first article's title and description. Route Configuration: Inside the beforeEach method, we create a route configuration using: await page.route('URL', async (route) => { ... }); Fetch the Response: Use await route.fetch() to complete the API call and store the result in a constant: const response = await route.fetch(); Modify the Response: Convert the response to JSON and update the title and description of the first article: responseBody.articles[0].title = 'This is a test title'; Fulfill the Modified Response: Use await route.fulfill() to send the modified response back to the application: await route.fulfill({ body: JSON.stringify(responseBody) }); Finally, we assert that the changes are reflected in the application by checking the updated title and description. Note that if you run the test without assertions, it may fail due to a known issue in Playwright. Using assertions allows enough time for the application to load the modified response. In summary, we intercepted the articles API call, modified the response, and fulfilled it back to the application. This process involves intercepting the URL, fetching the response, modifying it, and fulfilling the updated response. Thank you for watching, and see you in the next lesson!