Skip to content

Playwright API Mocking Tutorial: Test Web Apps Without a Live Backend

Learn how to intercept frontend API requests with Playwright 1.65.1, return custom JSON responses, simulate HTTP errors, and test web application states without depending on a live backend.

Playwright API Mocking Tutorial: Test Web Apps Without a Live Backend

On this page

Your frontend does not need a working backend every time you want to test a new feature. A product listing, customer dashboard, or search page can be tested with predictable API responses while the actual server is still under development. Playwright 1.65.1, released on November 13, 2026, provides browser network interception through its routing APIs, allowing developers to replace real HTTP responses with controlled test data. This tutorial shows how to configure a reusable API mocking workflow, test successful and failed requests, and verify that a web application handles both situations correctly.

The example uses Playwright Test with JavaScript and a fictional product management application. You will create a test environment that returns product records without contacting a backend, simulate a server error, and check that the frontend displays the expected result. The same approach works with applications built using React, Vue, Angular, or plain JavaScript, provided their browser requests match the routes configured in the tests.

Prepare the project before intercepting requests

Start with a Node.js project containing a frontend application that requests product information from /api/products. You need Node.js, npm, an existing web application, and permission to install development dependencies. Playwright Test is the test runner, while its browser automation APIs handle navigation, network interception, and assertions. Keep these tests separate from production application code so mock responses cannot accidentally become part of the live application.

Node.js and npm: A supported Node.js installation with npm available.
Frontend application: A page that requests data from /api/products.
Playwright Test: Version 1.65.1.
Browser: Chromium installed through Playwright.

Open a terminal in the project directory and install the required development dependency:

npm install --save-dev @playwright/test@1.65.1

Install the Chromium browser used by the example:

npx playwright install chromium

Create a Playwright configuration file named playwright.config.js:

import { defineConfig } from '@playwright/test';

export default defineConfig({
 testDir: './tests',
 use: {
 baseURL: 'http://127.0.0.1:3000',
 browserName: 'chromium'
 }
});

The baseURL setting allows tests to use relative application URLs rather than repeating the complete address. Change the port to match your development server. The official Playwright installation guide explains the supported installation and project configuration process.

Prepare the project before intercepting requests

Create a reusable product response

The first task is to prepare predictable data that the frontend can consume. Create a directory named tests and add a file called products.spec.js. This file will contain both successful and unsuccessful API scenarios. Keeping mock data inside the test file makes the example easy to understand, although larger projects can move shared fixtures into separate modules.

Start by defining two fictional products:

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

const products = [
 {
 id: 101,
 name: 'Wireless Keyboard',
 price: 45
 },
 {
 id: 102,
 name: 'USB-C Hub',
 price: 29
 }
];

These records represent the JSON response expected from the product endpoint. The application should render the product names when it receives this data. The important distinction is that the browser will receive these records directly from Playwright rather than from the actual backend. This allows the test to run independently of database contents and server availability.

Intercept the request and return mock JSON

Inside the test file, create a test that registers a route before navigating to the application. Playwright's page.route() method intercepts matching browser requests and passes control to a handler. That handler can fulfill the request with a custom response using route.fulfill(). The following example returns the two product records with an HTTP 200 status and the correct JSON content type.

test('displays products from a mocked API', async ({ page }) => {
 await page.route('**/api/products', async route => {
 await route.fulfill({
 status: 200,
 contentType: 'application/json',
 json: products
 });
 });

 await page.goto('/products');

 await expect(
 page.getByText('Wireless Keyboard')
 ).toBeVisible();

 await expect(
 page.getByText('USB-C Hub')
 ).toBeVisible();
});

The URL pattern **/api/products matches requests ending in the specified API path, regardless of the preceding hostname or path segments. Registering the route before navigation is important because the application might request its data immediately when the page loads. The json option supplies a JSON response, so you do not need to manually serialize the JavaScript array or construct the response body yourself.

The official API mocking documentation explains how to replace requests, modify existing responses, and replay previously recorded network traffic. For this example, direct response fulfillment is the simplest option because the test does not need a real API call.

Intercept the request and return mock JSON

Test how the frontend handles a server failure

A successful response is only half the job. A production application must also handle unavailable services, unexpected server responses, and failed requests without leaving users staring at an empty page. Playwright can simulate these situations by changing the status code and response body returned by the same intercepted endpoint. An HTTP 503 response represents a service that is temporarily unavailable, making it useful for testing an error state.

Add another test to products.spec.js:

test('displays an error when the API is unavailable', async ({ page }) => {
 await page.route('**/api/products', async route => {
 await route.fulfill({
 status: 503,
 contentType: 'application/json',
 json: {
 message: 'Service temporarily unavailable'
 }
 });
 });

 await page.goto('/products');

 await expect(
 page.getByText('Unable to load products')
 ).toBeVisible();
});

This test assumes that the frontend converts a failed product request into the message Unable to load products. If your application uses a different error message, update the assertion to match its actual behavior. A useful error state should communicate the problem and, where appropriate, provide a retry action instead of silently displaying an empty product list.

Run the tests and check the results

Once both scenarios are in place, execute the Playwright test runner from the project directory:

npx playwright test

Playwright starts the configured browser, executes the tests, and evaluates their assertions. The successful scenario should pass when both product names become visible. The failure scenario should pass when the frontend displays its expected error message after receiving the simulated HTTP 503 response. If either assertion fails, investigate the frontend behavior and route matching before assuming the browser automation itself is broken.

For more detailed failure information, enable the HTML reporter in the configuration:

npx playwright test --reporter=html

After execution, open the generated report with:

npx playwright show-report

The report helps identify failed assertions and the corresponding test. Playwright's Trace Viewer documentation also explains how to inspect recorded test activity, including network requests and responses when tracing is enabled.

Worked example: Product dashboard without a backend

Suppose a frontend developer is building a product dashboard at http://127.0.0.1:3000/products. The backend team has not finished its product endpoint, but the frontend needs to be checked before the integration is available.

  • Request: GET /api/products
  • Successful response: HTTP 200
  • First product: ID 101, Wireless Keyboard, $45
  • Second product: ID 102, USB-C Hub, $29
  • Failure response: HTTP 503
  • Expected success: Both product names appear.
  • Expected failure: Unable to load products appears.

Both scenarios use the same frontend page and endpoint. Only the intercepted response changes, allowing the developer to verify two different application states without modifying the backend.

Understand the problems that can make mocking fail

One common problem is registering a route after the application has already made its request. The original request may have reached the server before the interception handler was installed, so define the route before calling page.goto(). Another issue is an incorrect URL pattern: if the frontend requests /api/v2/products while the test intercepts /api/products, the handler will not match. Check the actual request URL and HTTP method when a mock response is not being returned.

Service Workers can also affect request interception because they may handle browser requests before Playwright's normal routing mechanism sees them. If a service-worker-based application prevents expected interception, consider configuring the browser context with serviceWorkers: 'block' for the relevant tests. Also remember that enabling Playwright routing disables the browser's HTTP cache, so these tests do not reproduce every caching behavior of an ordinary browsing session.

Mocked responses cannot establish that the real backend implements the same contract, handles database operations correctly, or enforces authorization. They verify frontend behavior against the responses you supply. Keep separate integration tests for the real API, particularly for authentication, permissions, data persistence, and business rules.

Make the mock suite reusable across frontend features

After the first tests work, move shared response data and frequently used route handlers into reusable test fixtures. You can create separate scenarios for empty product lists, missing fields, HTTP 401 Unauthorized, HTTP 404 Not Found, and HTTP 500 Internal Server Error. Each scenario should represent a meaningful frontend state rather than adding arbitrary status codes that the application does not handle differently.

For larger projects, use browser-context routing when multiple pages need the same mock, or save representative network responses in HTTP Archive (HAR) files when a collection of requests must be replayed consistently. Keep those recordings updated deliberately because HAR replay matches request URLs and methods, and POST requests must also match their recorded payloads. Start by automating the endpoints that block frontend development most often, then add the tests to continuous integration so changes to the interface do not silently break its handling of API responses.

Share this post

Muhammad Saleem profile photo

Written by

Muhammad Saleem

I’m Muhammad Saleem, a web developer and the owner of TechWare House, a software house focused on practical web and software solutions. With over 14 years of experience, I’ve built and managed hundreds of websites and custom , PHP/MySQL, Python, Django applications. I share hands-on insights about web development, software, technology, and digital solutions on WizTechnoz.com

166 posts published

All posts by this author

Copy this post

0 Comments

No comments yet. Be the first to share your thoughts.

Join the conversation

Log in or create a free account to leave a comment. You can edit or delete your own comments any time.