Network and API
Network Testing in Playwright
Network Testing in Playwright: definition, request/response validation, examples, mistakes, interview notes, and practice.
Definition and Brief Explanation
Definition: Network testing in Playwright means observing browser requests and responses while the UI runs.
Explanation: Network checks help prove that a UI action called the expected endpoint, received the expected response, or handled a backend failure. They should complement UI assertions, not replace them.
Why It Matters
- It makes tests faster and more controlled when backend state matters.
- It lets you test success, failure, and edge cases without depending on unstable services.
- It helps verify that the UI sends or receives the expected API traffic.
- It supports clean setup for UI tests through API calls.
How It Works
- Identify the request or API state involved in the test.
- Set up the route, request context, or response wait before the UI action.
- Trigger the UI behavior.
- Assert both the page result and important request/response details when needed.
Syntax and Examples
Example 1: Observe requests
page.on('request', request => console.log(request.url()));
Explanation: Logs browser requests for debugging network behavior.
Common Mistakes
- Mocking so much that the test no longer checks real integration.
- Using URL patterns that match unrelated requests.
- Creating shared backend data that breaks parallel tests.
- Forgetting the UI assertion after network setup.
Interview Notes
- What problem does Network Testing solve?
- When would you mock instead of using the real API?
- How do you avoid over-mocking?
- How do network waits differ from UI assertions?
Practice Task
Create a small Playwright example for Network Testing. Add one positive assertion, one note about what can go wrong, and one improvement that would make the test more maintainable.