Introduction
Learning how to mock API response in Playwright is an essential skill for QA Automation Engineers, SDETs, Selenium engineers transitioning to Playwright, software testing students, and developers. Modern web applications rely heavily on REST APIs to fetch data, authenticate users, process payments, and update dashboards. If these APIs become unavailable, slow, or return inconsistent data, automated UI tests can become unreliable.
Playwright provides built-in network interception capabilities that allow you to mock API responses without modifying the backend service. This helps teams build stable, repeatable, and faster automated tests while reducing dependency on external systems.
In this how to mock API response in Playwright tutorial, you will learn:
- What API response mocking is
- Why API mocking is important
- How to use page.route() and route.fulfill()
- Complete Playwright TypeScript examples
- Real-world enterprise scenarios
- Best practices
- Troubleshooting tips
- Playwright interview questions
What Is API Response Mocking in Playwright?
API response mocking is the process of intercepting a network request and returning a custom response instead of calling the real server.
Instead of:
Browser
│
▼
Real Backend API
Playwright can return a fake response:
Browser
│
▼
Playwright Mock Response
This allows your application to behave as though it received data from the backend while keeping the test independent of external services.
Common Use Cases
- UI testing without backend availability
- Testing edge cases
- Simulating server failures
- Testing offline behavior
- Automating CI/CD pipelines
- Performance testing with predictable data
Benefits of Mocking API Responses in Playwright
Understanding how to mock API response in Playwright provides several advantages:
- Faster test execution
- Stable and repeatable test results
- Reduced dependency on backend environments
- Easier testing of rare error conditions
- Improved CI/CD reliability
- Better developer and tester collaboration
- Simplified automation for frontend teams
Step-by-Step Tutorial: How to Mock API Response in Playwright
Step 1: Intercept an API Request
Use page.route() to intercept the request.
import { test, expect } from ‘@playwright/test’;
test(‘Intercept API’, async ({ page }) => {
await page.route(‘**/api/users’, async route => {
await route.fulfill({
status: 200,
contentType: ‘application/json’,
body: JSON.stringify([
{
id: 1,
name: ‘John’
}
])
});
});
await page.goto(‘https://example.com’);
});
Explanation
This code intercepts the /api/users request and returns a mocked JSON response instead of contacting the real API.
Practical use case: Testing a user dashboard without depending on a live backend.
Step 2: Mock a JSON Response
await page.route(‘**/products’, async route => {
await route.fulfill({
status: 200,
contentType: ‘application/json’,
body: JSON.stringify({
products: [
{
id: 101,
name: ‘Laptop’
},
{
id: 102,
name: ‘Keyboard’
}
]
})
});
});
Expected Behavior
The application displays mocked products exactly as if they were returned by the real API.
Step 3: Mock an Error Response
await page.route(‘**/orders’, async route => {
await route.fulfill({
status: 500,
contentType: ‘application/json’,
body: JSON.stringify({
message: ‘Internal Server Error’
})
});
});
Practical Use Case
Validate how the application handles server failures and displays error messages.
Step 4: Mock Authentication APIs
Authentication endpoints are frequently mocked during UI testing.
await page.route(‘**/login’, async route => {
await route.fulfill({
status: 200,
contentType: ‘application/json’,
body: JSON.stringify({
token: ‘mock-jwt-token’,
username: ‘admin’
})
});
});
Why It Matters
This allows you to bypass authentication dependencies while testing protected pages.
Step 5: Mock Dynamic JSON Responses
Playwright allows generating responses dynamically.
await page.route(‘**/profile’, async route => {
const response = {
id: Date.now(),
username: ‘playwrightUser’,
role: ‘QA Engineer’
};
await route.fulfill({
status: 200,
contentType: ‘application/json’,
body: JSON.stringify(response)
});
});
Practical Use Case
Simulate unique users or dynamic datasets for different test scenarios.
Real-World API Mocking Examples
1. Mock REST APIs
await page.route(‘**/customers’, async route => {
await route.fulfill({
status: 200,
contentType: ‘application/json’,
body: JSON.stringify([
{
id: 1,
name: ‘Alice’
}
])
});
});
Scenario: Customer management dashboard.
2. Mock Authentication Service
await page.route(‘**/auth’, async route => {
await route.fulfill({
status: 200,
body: JSON.stringify({
authenticated: true
})
});
});
Scenario: Login testing without an identity provider.
3. Mock HTTP 404
await page.route(‘**/users’, async route => {
await route.fulfill({
status: 404,
body: JSON.stringify({
message: ‘User Not Found’
})
});
});
Scenario: Verify “Record Not Found” pages.
4. Mock Network Failure
await page.route(‘**/payments’, async route => {
await route.abort();
});
Scenario: Test offline behavior and retry logic.
5. Mock Slow API Response
await page.route(‘**/reports’, async route => {
await new Promise(resolve => setTimeout(resolve, 3000));
await route.fulfill({
status: 200,
body: JSON.stringify({
report: ‘Monthly Sales’
})
});
});
Scenario: Validate loading spinners and progress indicators.
Playwright API Mocking vs Selenium
| Feature | Playwright | Selenium |
| Built-in API mocking | ✅ Yes | ❌ No |
| Network interception | ✅ Yes | Requires external tools |
| Route handling | page.route() | Browser plugins or proxies |
| Mock JSON | Native support | Third-party libraries |
| Offline simulation | Built-in | External setup |
| Beginner Friendly | Excellent | Moderate |
Why Playwright Stands Out
Unlike Selenium, Playwright includes built-in network interception APIs, making API mocking easier, faster, and more maintainable without relying on proxy servers or browser extensions.
Best Practices for API Mocking in Playwright
Follow these best practices for reliable automation:
- Mock only the APIs required for the current test.
- Keep mocked JSON responses realistic.
- Store reusable mock data in separate JSON files.
- Use descriptive route patterns.
- Test both success and failure responses.
- Validate UI changes after mocking.
- Avoid excessive mocking that hides integration issues.
- Include API mocking tests in your CI/CD pipeline.
Common Issues & Troubleshooting Tips
| Problem | Solution |
| Route not intercepted | Verify the URL pattern matches the actual request. |
| Mock not applied | Register page.route() before calling page.goto(). |
| Incorrect JSON | Validate JSON syntax and response structure. |
| Multiple routes conflict | Use specific route patterns instead of broad wildcards. |
| UI not updating | Ensure the frontend consumes the mocked response correctly. |
Playwright API Mocking Interview Questions with Answers
1. What is API response mocking?
API response mocking intercepts HTTP requests and returns custom responses without calling the real backend.
2. Which Playwright API is used for mocking?
Use:
page.route()
3. How do you return a custom response?
Use:
route.fulfill()
4. How do you simulate a server error?
Return a mocked response with an HTTP status such as 500 using route.fulfill().
5. Why is API mocking useful in automation?
It improves test speed, reliability, repeatability, and enables testing of scenarios that are difficult to reproduce with a live backend.
FAQs
What is how to mock API response in Playwright?
It is the process of intercepting network requests using Playwright and returning custom responses with APIs such as page.route() and route.fulfill() instead of contacting a real backend server.
How do I get started with how to mock API response in Playwright?
Install Playwright, identify the API endpoint you want to intercept, use page.route() to capture the request, return a mocked response with route.fulfill(), and verify the application’s behavior using Playwright assertions.
Is how to mock API response in Playwright suitable for beginners?
Yes. Playwright provides straightforward APIs for network interception, making API response mocking easy to learn for beginners while remaining powerful enough for enterprise automation projects.
