Network and API
Route Mocking in Playwright
Route Mocking in Playwright: definition, request interception, fulfill examples, mistakes, interview notes, and practice.
Definition and Brief Explanation
Definition: Route mocking in Playwright intercepts matching network requests and lets the test fulfill, modify, abort, or continue them.
Explanation: Mocking is useful for error states, slow services, third-party calls, and controlled data. The key is to mock only what the test needs so the UI still proves meaningful behavior.
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: Mock API response
await page.route('**/api/user', route => route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ name: 'Shariq' })
}));
Explanation: The browser receives this mocked response instead of calling the real API.
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 Route Mocking 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 Route Mocking. Add one positive assertion, one note about what can go wrong, and one improvement that would make the test more maintainable.