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:
- Create a Promise to wait for the response before triggering the action.
- Perform the action that causes the network request.
- 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.
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.
---
Guy Arieli is the Chief Technology Officer at BlinqIO, a company building AI-powered test engineering tools for Playwright. With a deep passion for developer productivity and test automation, Guy shares practical insights from real-world use cases.
Want to contribute your own tips? Reach out to us at tips@playwright-user-event.org.