How to Mock an API in React Tests with Playwright’s page.route
You can replace the API responses a React screen receives with page.route in Playwright Test (API mocking). Without running a backend server, you can test the list display, server errors (500), network failures, and the loading display one at a time. Error screens that are hard to trigger with a real server can also be reproduced by returning the response you choose in the test.
In a test environment, I wrote and ran five tests that replace responses for a "cat list" screen built with Vite, React, and TypeScript. I also show, with actual output, two things I found while testing: the React StrictMode makes the request twice, and a URL with a query string does not match a pattern.
The test environment is Ubuntu 24.04, Node.js 22.23.4, and npm 10.9.9. I used react / react-dom 19.3.1, vite 8.3.8, @vitejs/plugin-react 6.3.0, typescript 7.0.2, and @playwright/test 1.63.0, and only Chromium as the browser. I did not try Firefox or WebKit, running on a CI service, route.fetch (fetching the real response and modifying part of it), replacing with HAR files, or apps that use a Service Worker.
- 1. The screen under test
- 2. Replacing the list response
- 3. Returning 500 to check the error and the reload
- 4. Checking a network failure and the loading display
- 5. Checking the body sent by POST
- 6. With StrictMode, a test that switches responses by call count fails
- 7. A pattern that does not match the query string is not replaced
The screen under test
When the screen opens, it loads the cat list with GET /api/cats?sort=name. Depending on the response state, it shows a loading message, an error message with a reload button, or the list. If you enter a name in the form below the list and press the Add button, it sends the name to POST /api/cats and appends the returned cat to the end of the list.
The test environment has no server that returns /api/cats. The tests replace the responses in the test itself to switch between these three screens.

The component works as follows. fetch does not fail when the server returns 500; it returns a response with res.ok set to false. So the code checks res.ok and raises an error itself. On the other hand, when the request itself fails, such as when the server cannot be reached, fetch fails with a TypeError (see MDN's fetch documentation). The two cases are separated and show different messages.
// src/App.tsx
import { useEffect, useState } from 'react';
import type { FormEvent } from 'react';
type Cat = { id: number; name: string };
type State =
| { type: 'loading' }
| { type: 'error'; message: string }
| { type: 'done'; cats: Cat[] };
export default function App() {
const [state, setState] = useState<State>({ type: 'loading' });
const [reload, setReload] = useState(0);
const [name, setName] = useState('');
useEffect(() => {
let ignore = false;
setState({ type: 'loading' });
fetch('/api/cats?sort=name')
.then(async (res) => {
if (!res.ok) throw new Error(`読み込みに失敗しました(${res.status})`);
return (await res.json()) as Cat[];
})
.then((cats) => {
if (!ignore) setState({ type: 'done', cats });
})
.catch((e: unknown) => {
if (ignore) return;
const message =
e instanceof TypeError ? 'サーバーに接続できませんでした' : (e as Error).message;
setState({ type: 'error', message });
});
return () => {
ignore = true;
};
}, [reload]);
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const res = await fetch('/api/cats', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name }),
});
const created = (await res.json()) as Cat;
setState((prev) =>
prev.type === 'done' ? { type: 'done', cats: [...prev.cats, created] } : prev,
);
setName('');
}
return (
<main>
<h1>猫の一覧</h1>
{state.type === 'loading' && <p>読み込み中…</p>}
{state.type === 'error' && (
<div role="alert">
<p className="error">{state.message}</p>
<button type="button" onClick={() => setReload((n) => n + 1)}>
もう一度読み込む
</button>
</div>
)}
{state.type === 'done' && (
<>
{state.cats.length === 0 ? (
<p>まだ猫がいません</p>
) : (
<ul>
{state.cats.map((cat) => (
<li key={cat.id}>{cat.name}</li>
))}
</ul>
)}
<form onSubmit={handleSubmit}>
<label>
名前
<input value={name} onChange={(e) => setName(e.target.value)} />
</label>
<button type="submit">追加</button>
</form>
</>
)}
</main>
);
}
main.tsx keeps the default Vite template, which wraps App in <StrictMode>. This affects the number of requests, as explained later.
In the Playwright config, npm run dev starts the Vite development server before the tests run. In this article, I ran with CI=1 so that Playwright starts the development server every time (for reuseExistingServer, see the official web server documentation).
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
use: {
baseURL: 'http://localhost:5173',
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
webServer: {
command: 'npm run dev',
url: 'http://localhost:5173',
reuseExistingServer: !process.env.CI,
},
});
Replacing the list response
Here is the most basic form. If you pass a URL pattern and a function to page.route, any request that matches the pattern is passed to that function. Calling route.fulfill inside the function returns the values you pass as the response, without contacting the server. If you pass a value to json, it becomes the JSON body, and Content-Type is set to application/json.
// e2e/cats.spec.ts
import { test, expect } from '@playwright/test';
test('APIが返した一覧を表示する', async ({ page }) => {
await page.route('**/api/cats?*', (route) =>
route.fulfill({
json: [
{ id: 1, name: 'たま' },
{ id: 2, name: 'みけ' },
],
}),
);
await page.goto('/');
await expect(page.getByRole('listitem')).toHaveText(['たま', 'みけ']);
});
This screen loads the list right after it opens, so I call page.route before page.goto. The official API mocking example also replaces responses before the page is opened.
The pattern **/api/cats?* matches a URL where /api/cats? is followed by a string that does not contain /. In Playwright patterns, * means "a sequence of characters other than /," and ** means "a sequence of characters that may include /." ? is not a wildcard for one character; it matches only the literal ? character (see the URL pattern documentation). I tested what happens when you forget the ?* in the last section.
Returning 500 to check the error and the reload
To reproduce a server error, pass 500 as status to route.fulfill (if omitted, it defaults to 200). In this test, the first response is 500, and after the Reload button is pressed, the list is returned.
test('500が返ると、エラーと再読み込みのボタンを出す', async ({ page }) => {
let failing = true;
await page.route('**/api/cats?*', (route) => {
if (failing) return route.fulfill({ status: 500, body: 'Internal Server Error' });
return route.fulfill({ json: [{ id: 1, name: 'たま' }] });
});
await page.goto('/');
await expect(page.getByRole('alert')).toContainText('読み込みに失敗しました(500)');
failing = false;
await page.getByRole('button', { name: 'もう一度読み込む' }).click();
await expect(page.getByRole('listitem')).toHaveText(['たま']);
});
The response is switched by the variable failing in the test. After confirming the error appears, it is set to false and the button is pressed. I also tried a version that switches based on the call count ("only the first request returns 500"), but it failed in this screen. The reason is explained in a later section.
Checking a network failure and the loading display
A server that cannot be reached can be simulated with route.abort. It fails the request without returning a response, so the screen's fetch fails with a TypeError, and the connection error message appears. route.abort accepts an error code; if omitted, it is failed (a generic failure).
test('サーバーにつながらないと、接続のエラーを出す', async ({ page }) => {
await page.route('**/api/cats?*', (route) => route.abort());
await page.goto('/');
await expect(page.getByRole('alert')).toContainText('サーバーに接続できませんでした');
});
For the loading display, the test controls when the response is returned. Once page.route is registered, a matching request stays pending until the function calls fulfill, continue, or abort (see the page.route documentation). So I made the function wait on a Promise, confirmed the loading message, and then returned the response with release().
test('応答が届くまで、読み込み中と表示する', async ({ page }) => {
let release!: () => void;
const released = new Promise<void>((resolve) => (release = resolve));
await page.route('**/api/cats?*', async (route) => {
await released;
await route.fulfill({ json: [] });
});
await page.goto('/');
await expect(page.getByText('読み込み中…')).toBeVisible();
release();
await expect(page.getByText('まだ猫がいません')).toBeVisible();
await expect(page.getByText('読み込み中…')).toHaveCount(0);
});
This lets you check the display both before and after the response is returned, in sequence.
Checking the body sent by POST
The add-form test also checks what the screen sent. You can get the request information with route.request(), read the method with method(), and read the body as JSON with postDataJSON().
test('追加すると、入力した名前をPOSTで送る', async ({ page }) => {
await page.route('**/api/cats?*', (route) => route.fulfill({ json: [] }));
await page.route('**/api/cats', async (route) => {
const request = route.request();
expect(request.method()).toBe('POST');
expect(request.postDataJSON()).toEqual({ name: 'くろ' });
await route.fulfill({ status: 201, json: { id: 10, name: 'くろ' } });
});
await page.goto('/');
await page.getByLabel('名前').fill('くろ');
await page.getByRole('button', { name: '追加' }).click();
await expect(page.getByRole('listitem')).toHaveText(['くろ']);
});
Two patterns are registered here. **/api/cats matches only /api/cats without a ?, and **/api/cats?* matches only the list request with ?sort=name. So the list GET never reaches the POST handler.
I also checked that the test fails when the expect inside the function does not match. I ran a copy of the file where the expected name was changed to "Shiro", and it failed, showing the difference from toEqual (part of the output):
✘ 5 [chromium] › e2e/post-wrong.spec.ts:51:1 › 追加すると、入力した名前をPOSTで送る (294ms)
Error: expect(received).toEqual(expected) // deep equality
- Expected - 1
+ Received + 1
Object {
- "name": "しろ",
+ "name": "くろ",
}
When I ran all five tests above together, they all passed:
$ CI=1 npx playwright test e2e/cats.spec.ts --reporter=list; echo "exit=$?"
Running 5 tests using 1 worker
✓ 1 [chromium] › e2e/cats.spec.ts:3:1 › APIが返した一覧を表示する (245ms)
✓ 2 [chromium] › e2e/cats.spec.ts:16:1 › 500が返ると、エラーと再読み込みのボタンを出す (259ms)
✓ 3 [chromium] › e2e/cats.spec.ts:30:1 › サーバーにつながらないと、接続のエラーを出す (209ms)
✓ 4 [chromium] › e2e/cats.spec.ts:36:1 › 応答が届くまで、読み込み中と表示する (224ms)
✓ 5 [chromium] › e2e/cats.spec.ts:51:1 › 追加すると、入力した名前をPOSTで送る (300ms)
5 passed (2.8s)
exit=0
With StrictMode, a test that switches responses by call count fails
I also tried the 500 test by counting the requests and making only the first one return 500:
test('1回目だけ500を返す(回数で切り替える)', async ({ page }) => {
let calls = 0;
await page.route('**/api/cats?*', (route) => {
calls++;
if (calls === 1) return route.fulfill({ status: 500, body: 'Internal Server Error' });
return route.fulfill({ json: [{ id: 1, name: 'たま' }] });
});
await page.goto('/');
await expect(page.getByRole('alert')).toContainText('読み込みに失敗しました(500)');
});
This test failed because the error message could not be found. Looking at error-context.md, which Playwright saves on failure, the screen showed the list with "Tama" instead of an error. The terminal output was (part of it):
Error: expect(locator).toContainText(expected) failed
Locator: getByRole('alert')
Expected substring: "読み込みに失敗しました(500)"
Timeout: 5000ms
Error: element(s) not found
Counting the requests to /api/cats when the screen opens gave 2 (part of the output):
通信の回数: 2
✓ 1 [chromium] › e2e/count.spec.ts:3:1 › 最初に開いたときの /api/cats への通信を数える (348ms)
React's StrictMode runs Effects one extra time, only during development. The first Effect is cleaned up right away (ignore becomes true), and its result is discarded. The screen uses the response from the second request. When I switched by call count, the first request, which is discarded, got the 500, and the screen showed the list from the second request.
I temporarily removed <StrictMode> from main.tsx and ran again. There was one request, and the test that switches by call count passed (part of the output):
通信の回数: 1
✓ 1 [chromium] › e2e/count.spec.ts:3:1 › 最初に開いたときの /api/cats への通信を数える (431ms)
✓ 2 [chromium] › e2e/retry-count.spec.ts:3:1 › 1回目だけ500を返す(回数で切り替える) (456ms)
A pattern that does not match the query string is not replaced
Finally, here is a test that uses the pattern **/api/cats instead of **/api/cats?*:
test('パターンに ?* を付けずに差し替える', async ({ page }) => {
await page.route('**/api/cats', (route) => route.fulfill({ json: [{ id: 1, name: 'たま' }] }));
await page.goto('/');
await expect(page.getByRole('listitem')).toHaveText(['たま']);
});
This test failed after waiting 5 seconds, with no list items found. The screen content saved in error-context.md is below. It shows an error that the JSON could not be read:
- main [ref=e3]:
- heading "猫の一覧" [level=1] [ref=e4]
- alert [ref=e5]:
- paragraph [ref=e6]: Unexpected token '<', "<!doctype "... is not valid JSON
- button "もう一度読み込む" [ref=e7]
A pattern has to match the entire URL (see the URL pattern documentation). **/api/cats does not match a URL with ?sort=name, so the request was not replaced and reached the Vite development server. When I sent the same URL to the development server with curl, it returned 200 OK with Content-Type: text/html, which was the app's HTML:
$ curl -s -i 'http://localhost:5173/api/cats?sort=name' | head -5; echo; curl -s 'http://localhost:5173/api/cats?sort=name' | head -3
HTTP/1.1 200 OK
Vary: Origin
Content-Type: text/html
Cache-Control: no-cache
Etag: W/"262-jTvT37rIKggjZPfoIHfBJpBLdkQ"
<!doctype html>
<html lang="en">
<head>
The status was 200, so res.ok was true, and the attempt to read the HTML as JSON raised an error. The test I meant to mock ended up reading the HTML returned by the development server. If the mocked screen shows an error like "is not valid JSON", first check whether the pattern matches the entire URL.





