📣 Requestly API Client – Free Forever & Open Source. A powerful alternative to Postman. Try now ->

The Ultimate Guide to Mocking APIs with Playwright

Rohit Rajpal
Learn how to mock APIs with Playwright and explore advanced techniques, including conditional mocking, HAR files, and dynamic responses.

Mocking APIs with Playwright allows you to control network responses during automated tests. Instead of calling a live backend, you can intercept requests and return predefined data. This makes tests faster, more reliable, and easier to run in environments where the real API is unavailable or unstable.

This guide covers the fundamentals, advanced mocking techniques, and practical examples for applying API mocking in real testing workflows.

What Does It Mean to Mock APIs with Playwright?

Mocking APIs with Playwright involves intercepting network requests made during test execution and returning predefined responses instead of calling the actual API. This allows full control over how the application under test behaves in different situations.

It is especially useful when:

  1. The backend service is not ready for integration
  2. The API is unreliable or undergoing frequent changes
  3. There is a need to test specific scenarios that are hard to reproduce with live data

By using Playwright’s page.route() method, requests can be matched by URL patterns, HTTP methods, or query parameters, and responses can be customized with static data, dynamic logic, or files that replicate production-like payloads. This approach ensures tests remain predictable and do not break due to changes in external systems.

Why Mock APIs with Playwright?

Mocking APIs in Playwright helps control test variables, target hard-to-reproduce scenarios, and verify application behavior under both ideal and adverse conditions.

Below are the key reasons to mock APIs with Playwright.

  1. Stable and repeatable results: Live APIs can return different data over time due to database changes, feature rollouts, or environment differences. By serving predefined responses, tests can run with the same data set every time, making failures easier to diagnose.
  2. Faster execution: External API calls can introduce delays due to network latency or server processing time. Mocking skips the round trip entirely, which reduces execution time and allows more tests to be run in the same CI/CD cycle.
  3. Controlled data scenarios: Certain application features depend on rare or complex API states, such as empty lists, large datasets, or specific error codes. Mocking makes it possible to simulate these states on demand without waiting for them to occur naturally.
  4. Error condition simulation: Backend systems often handle errors differently depending on the source of failure. By mocking responses, testers can easily trigger 500 errors, timeouts, invalid payload formats, or permission issues to confirm the application handles them correctly.
  5. Independence from backend readiness: Frontend teams can continue building and testing even if the backend API is incomplete or undergoing changes, keeping delivery schedules on track.

Getting Started: How to Mock APIs with Playwright

Mocking APIs in Playwright begins with setting up the testing framework and understanding how network interception works. At a high level, the process involves preparing Playwright, deciding how to structure mock data, and validating a basic mock before moving to advanced scenarios.

The key starting points are:

  1. Framework setup: Install Playwright, configure it for the browsers you need, and verify it runs correctly in your environment.
  2. Learning request interception: Understand how page.route() captures and modifies matching network requests.
  3. Organizing mock data: Keep JSON payloads or templates in a structured location so they can be updated without changing test logic.
  4. (Recommended) Run an initial mock: Replace one API call with static data to confirm that interception is working before adding more complex mocks.

Once these basics are in place, the next step is to follow a structured workflow to implement API mocks for real test scenarios.

Step-by-Step Guide to Mock APIs with Playwright

The following process shows how to intercept an API request in Playwright, return custom data, and verify it in the application.

1. Create a new test file

Create a file such as mock-api.spec.js in your Playwright test directory. Import the Playwright test runner.

import { test, expect } from '@playwright/test';

2. Launch the browser and create a page context

Inside the test, launch a browser instance and create a new page.

test('mock API example', async ({ page }) => 
{ // Step 3 will go here
});

3. Intercept the target API request

Use page.route() to match a request. The example below intercepts all calls to /api/users.

await page.route('**/api/users', async route => 
{ // Step 4 will go here
});

You can use ** as a wildcard for any part of the URL, or use exact matches or regex patterns for more control.

4. Return the mock response

Inside the route handler, respond with static data and headers.

await page.route('**/api/users', async route => 
{ const mockData = [ 
{ id: 1, name: 'Alice Johnson' }, 
{ id: 2, name: 'Mark Daniels' } 
]; 
await route.fulfill({ 
status: 200, 
contentType: 'application/json', 
body: JSON.stringify(mockData)
 });
});

5. Trigger the request from the application

Navigate to the page that makes the API call. This ensures your mock is used instead of the live API.

await page.goto('https://example.com/users');

6. Run assertions on the UI

Verify that the mocked data appears as expected.

await expect(page.locator('text=Alice Johnson')).toBeVisible();
await expect(page.locator('text=Mark Daniels')).toBeVisible();

7. Clean up after the test

Closing the context is handled automatically by Playwright’s test runner, but in custom scripts, ensure you close the browser to avoid resource leaks.

Advanced Techniques to Mock APIs with Playwright

Once the basics are in place, mocking in Playwright can be extended to handle conditional responses, simulate network issues, or replay real traffic. These techniques make tests more realistic and better at covering edge cases.

1. Conditional Mocking of API Requests

Use conditional mocking when an endpoint needs to return different responses based on input values. For example, a user API can return an admin user if the request specifies an admin role, and a regular user otherwise. This approach lets you test multiple scenarios without creating separate mock files.

Example: Returning different user data based on a query parameter.

await page.route('**/api/users', async route => {
const url = new URL(route.request().url());
const role = url.searchParams.get('role');
if (role === 'admin') {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([{ id: 1, name: 'Admin User' }])
});
} else {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([{ id: 2, name: 'Regular User' }])
});
}
});

2. Simulating Network Conditions (Delays or Timeouts)

Simulate network delays or timeouts to test how your application handles slow responses or time-sensitive operations. For instance, adding a delay allows you to verify loading indicators, spinners, or timeout handling logic in the UI.

Example: Adding a 2-second delay.

await page.route('**/api/data', async route => { 
await new Promise(resolve => setTimeout(resolve, 2000)); // 2-second delay 
await route.fulfill({ 
status: 200, 
contentType: 'application/json', 
body: JSON.stringify({ message: 'Delayed response' })
});
});

3. Using HAR Files for Realistic API Mocks

Replay real API traffic with HAR files to test your application against realistic responses. This method ensures mocks reflect actual production data without relying on live servers, making tests more accurate and reliable.

Example:

// Record a HAR file beforehand using Playwright CLI or browser dev tools
await context.routeFromHAR('path/to/recorded.har', 
{ update: false, // Replay mode
});

This approach ensures your mocks reflect actual production responses without making live calls.

4. Mocking Secure and HTTPS API Requests

Intercept HTTPS API calls the same way as HTTP calls to test secure endpoints. This allows you to mock sensitive APIs without additional SSL configuration while ensuring your application behaves correctly with secure connections.

Example:

await page.route('https://secure.example.com/api/secure-data', async route => { 
await route.fulfill({ 
status: 200,
 contentType: 'application/json', 
body: JSON.stringify({ token: 'mock-token', status: 'ok' }) 
});
});

5. Dynamic Mock Responses Based on Request Body

Return different results depending on the request payload, which is especially useful for POST or PUT endpoints. For example, an orders API can respond with “Expedited” for high-priority requests and “Standard” for others, letting you cover multiple backend logic paths in one test.

Example:

await page.route('**/api/orders', async route => { 
const postData = route.request().postDataJSON(); 
if (postData.priority === 'high') { 
await route.fulfill({ 
status: 200, 
contentType: 'application/json', 
body: JSON.stringify({ orderId: 123, status: 'Expedited' }) 
}); 
} else { await route.fulfill({ 
status: 200, 
contentType: 'application/json', 
body: JSON.stringify({ orderId: 456, status: 'Standard' }) 
}); 
}
});

6. Intercepting and Modifying Live Responses

Fetch the actual API response and modify parts of it to simulate specific scenarios or test edge cases. This approach lets you inject test data, hide sensitive fields, or adjust backend responses while keeping the rest of the data close to production.

Example:

await page.route('**/api/products', async route => 
{ const response = await route.fetch(); // Get real API data 
const json = await response.json(); 
json.push({ id: 999, name: 'Mocked Product' }); // Inject test item 
await route.fulfill({ 
response, 
body: JSON.stringify(json) 
});
});

Why Use Requestly to Mock APIs with Playwright

Requestly provides a flexible and powerful way to manage API mocks without modifying Playwright test scripts. It allows teams to simulate backend responses, control external services, and create consistent test environments even when the actual APIs are unstable or unavailable.

Here are some ways Requestly enhances API mocking:

  1. Define and Manage Rules Instantly: Set up API mocks quickly, update them as needed, and organize rules in a central dashboard, eliminating repetitive changes in test code.
  2. Test Multiple Scenarios Efficiently: Switch API responses to cover edge cases, error conditions, or new features without redeploying the backend. This speeds up testing for complex workflows.
  3. Control External and Third-Party APIs: Safely mock services like payment gateways, analytics, or authentication APIs, ensuring stable test runs even when third-party systems are unreliable.
  4. Enable Team Collaboration: Share mock rules across team members or projects so everyone tests with consistent data and reduces duplication of effort.
  5. Ensure Cross-Browser Consistency: Apply the same API mocks across multiple browser contexts, keeping tests reliable regardless of the environment.
  6. Integrate Easily With Playwright Workflows: Requestly rules work alongside Playwright’s built-in mocking capabilities, allowing teams to combine the flexibility of Playwright scripts with centralized mock management.

Conclusion

Mocking APIs with Playwright is essential for building reliable, fast, and maintainable tests. From basic request interception to advanced techniques, such as conditional responses, partial modifications, and chained mocks, these strategies allow teams to simulate complex workflows, handle dynamic content, and test edge cases without depending on live backends.

Requestly provides centralized rule management and lets teams create and organize API mocks without changing test scripts. It simplifies scenario testing by allowing responses to be switched quickly to cover edge cases or new features. It also enables efficient mocking of external or third-party APIs while ensuring stable and consistent test environments.

author avatar
Rohit Rajpal
Rohit Rajpal is a B2B Content Strategist at BrowserStack, helping SaaS brands build AI-first strategies that drive authority and revenue. He writes about content, strategy, and the future of search in the zero-click era.
Written by
Rohit Rajpal
Rohit Rajpal is a B2B Content Strategist at BrowserStack, helping SaaS brands build AI-first strategies that drive authority and revenue. He writes about content, strategy, and the future of search in the zero-click era.

Related posts