Using waitForResponse in Playwright for Advanced Synchronization

Playwright’s built-in synchronization mechanisms cover most scenarios, but there are times when you need finer control over network requests. This is where waitForResponse shines. It allows you to wait for a specific network response, ensuring your test interacts with the app only after certain conditions are met. This tip explores how and why to use waitForResponse effectively, especially when actions trigger asynchronous requests.
Solution
In scenarios where performing an action triggers a network request, and you need to verify the content or status of the response, waitForResponse is invaluable. The correct order of operations is critical:
1. Create a Promise to wait for the response before triggering the action.
2. Perform the action that causes the network request.
3. Await the Promise to ensure the test continues only after the response is validated.
This sequence ensures Playwright listens for the response before the request is sent. If you reverse the order, Playwright might miss the response, leading to flaky tests.
Example
Here’s a scenario: After clicking a “Save” button, your app sends a POST request to save data. You want to verify the response contains a success message.
// Create a promise to wait for the specific response
const responsePromise = page.waitForResponse(response =>
response.url().includes('/api/save') && response.status() === 200
);
// Perform the action that triggers the request
await page.click('#save-button');
// Wait for the response and validate its body
const response = await responsePromise;
Summary
waitForResponse provides precise control in tests that depend on network activity. By creating the Promise before triggering the action, you guarantee that Playwright listens for the response at the right moment, avoiding race conditions. Use this tip when you need to validate network responses, ensuring your tests are robust and reliable.