QA and Test Automation · Lab 16 of 35
Network Mocking in Playwright: Test Every UI State (Lab)
Make ShopRung's API say anything and check the UI copes: an empty catalogue, a server error, a 111-character product name, going offline and a slow response, plus a spy that checks what the page sends. Six real tests, and one real usability finding.
⏱ 45 minIntermediate💸 Free6 steps
Node.js 22Playwright Test 1.63TypeScriptShopRung
Overview video
What you will build
A small Playwright project with 6 tests for UI states that real data almost never shows:
- An empty catalogue: the "No products match your search." message.
- A 500 error: the API's message shown to the shopper, not a blank page.
- A very long product name: the real response with one field changed, and the card still usable.
- Offline: the request aborted, and what the shop says (a real finding: the raw text "Failed to fetch").
- A slow API: the loading state shows first, then the products.
- A spy: the exact search term the page sends to the API.
Before you start
- Playwright end to end, or comfort with Playwright tests in TypeScript.
- The idea behind this lab: Network mocking.
- ShopRung installed, as in lab 1 setup.
Setup
S1Start ShopRung
Start ShopRung as in lab 1 with npm start, and leave it running. Some tests use its real answers.
curl http://localhost:8080/api/healthcurl http://localhost:8080/api/healthcurl.exe http://localhost:8080/api/health {"status":"UP","app":"ShopRung","version":"1.0.0"} S2Create the project
Make a folder shoprung-network-mocking and add the three files from step 1, then install. If you did the end-to-end lab, this is the same setup without the login.
mkdir shoprung-network-mocking
cd shoprung-network-mocking
# add package.json, .gitignore and playwright.config.ts from step 1, then:
npm install
npx playwright install chromium Project files
package.json, .gitignore and a config with traces kept for failures.
The same shape as the end-to-end lab. One difference: trace: 'retain-on-failure' keeps a trace for every failed test, because when a mocked test fails you want to see exactly what the route returned.
{
"name": "shoprung-network-mocking",
"private": true,
"scripts": {
"test": "playwright test",
"report": "playwright show-report"
},
"devDependencies": {
"@playwright/test": "1.63.0"
}
} node_modules/
playwright/.auth/
test-results/
playwright-report/ import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
workers: 1,
reporter: [['list'], ['html', { open: 'never' }]],
use: {
baseURL: process.env.BASE_URL ?? 'http://localhost:8080',
trace: 'retain-on-failure',
},
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
}); - Every failed test keeps its trace, including the network tab with your mocked responses.line 9
- One shared ShopRung, one test at a time.line 5
An empty catalogue and a server error
Two states you cannot get from ShopRung's real data: no products at all, and a 500.
Create tests/products-states.spec.ts. page.route(pattern, handler) puts your test between the page and the network: every request whose URL matches the pattern goes to your handler instead of the server. The pattern **/api/products?* matches the product list (it always has a ?), but not /api/products/categories.
route.fulfill answers the request yourself. The first test returns an empty list; ShopRung shows No products match your search. and 0 products. The second returns a 500 with an error body; ShopRung shows the API's message, Database unavailable.
Register routes before page.goto. ShopRung asks for the products as soon as it loads, so a route added afterwards is too late.
import { test, expect } from '@playwright/test';
// Every route is registered BEFORE page.goto, so the very first request is already intercepted.
const PRODUCTS = '**/api/products?*';
test('an empty catalogue shows a friendly message', async ({ page }) => {
await page.route(PRODUCTS, (route) => route.fulfill({ json: { count: 0, items: [] } }));
await page.goto('/');
await expect(page.getByTestId('no-results')).toHaveText('No products match your search.');
await expect(page.getByTestId('result-count')).toHaveText('0 products');
});
test('a server error shows the message from the API', async ({ page }) => {
await page.route(PRODUCTS, (route) => route.fulfill({
status: 500,
json: { error: 'internal', message: 'Database unavailable' },
}));
await page.goto('/');
await expect(page.getByTestId('error')).toHaveText('Database unavailable');
}); - A glob.
**is any start,?*needs a query string.line 4 - The page cannot tell this from a real answer.line 7
- Always set the status: an error body with 200 tests nothing.line 15
npx playwright test ✓ 1 [chromium] › tests/products-states.spec.ts:6:5 › an empty catalogue shows a friendly message ✓ 2 [chromium] › tests/products-states.spec.ts:13:5 › a server error shows the message from the API 2 passed (1.1s)
Stuck on this step?
- The test sees 12 products instead of none.
- The route was registered after
page.goto, or the pattern does not match. Logroute.request().url()inside the handler to see what arrives.
Change one field of the real response
Real data with one odd value: a product name 111 characters long.
Often you want the real response with one thing changed. Inside the handler, route.fetch() sends the request to ShopRung and returns the real response. Change one field, then route.fulfill({ response, json }) sends the edited body with the real status and headers.
The test makes the first product's name very long and checks the layout still works: all 12 cards render, the heading shows the full name, and the card's button is still on screen (toBeInViewport). Use the same trick for prices with many digits, missing optional fields or odd characters.
import { test, expect } from '@playwright/test';
// Every route is registered BEFORE page.goto, so the very first request is already intercepted.
const PRODUCTS = '**/api/products?*';
test('an empty catalogue shows a friendly message', async ({ page }) => {
await page.route(PRODUCTS, (route) => route.fulfill({ json: { count: 0, items: [] } }));
await page.goto('/');
await expect(page.getByTestId('no-results')).toHaveText('No products match your search.');
await expect(page.getByTestId('result-count')).toHaveText('0 products');
});
test('a server error shows the message from the API', async ({ page }) => {
await page.route(PRODUCTS, (route) => route.fulfill({
status: 500,
json: { error: 'internal', message: 'Database unavailable' },
}));
await page.goto('/');
await expect(page.getByTestId('error')).toHaveText('Database unavailable');
});
test('a very long product name still renders in its card', async ({ page }) => {
const longName = 'Extremely Long Product Name '.repeat(4).trim();
await page.route(PRODUCTS, async (route) => {
const response = await route.fetch(); // the real answer from ShopRung
const body = await response.json();
body.items[0].name = longName; // change one field
await route.fulfill({ response, json: body }); // everything else stays real
});
await page.goto('/');
await expect(page.getByTestId('product-card')).toHaveCount(12);
const card = page.getByTestId('product-card').first();
await expect(card.getByRole('heading', { name: longName })).toBeVisible();
await expect(card.getByRole('button')).toBeInViewport();
}); - The real answer from ShopRung.line 25
- One field changed. The other 11 products stay real.line 27
- A long name must not push the button off screen.line 34
npx playwright test 3 passed (1.3s)
Offline and slow
Two network conditions: no connection at all, and an answer that takes 1.5 seconds.
route.abort('internetdisconnected') fails the request as if the Wi-Fi dropped. ShopRung does not crash: it shows an error. But the error text is Failed to fetch, the browser's raw technical message, shown to a shopper. The test records what the shop does today, and the comment says what to raise: a message like "You seem to be offline. Try again." is what users need. Mocking found that in seconds.
The slow test holds the request for 1.5 seconds, then lets the real request through with route.continue(). First the page must show Loading…, then the 12 products. Without mocking, a fast local server never shows the loading state long enough to test it.
import { test, expect } from '@playwright/test';
// Every route is registered BEFORE page.goto, so the very first request is already intercepted.
const PRODUCTS = '**/api/products?*';
test('an empty catalogue shows a friendly message', async ({ page }) => {
await page.route(PRODUCTS, (route) => route.fulfill({ json: { count: 0, items: [] } }));
await page.goto('/');
await expect(page.getByTestId('no-results')).toHaveText('No products match your search.');
await expect(page.getByTestId('result-count')).toHaveText('0 products');
});
test('a server error shows the message from the API', async ({ page }) => {
await page.route(PRODUCTS, (route) => route.fulfill({
status: 500,
json: { error: 'internal', message: 'Database unavailable' },
}));
await page.goto('/');
await expect(page.getByTestId('error')).toHaveText('Database unavailable');
});
test('a very long product name still renders in its card', async ({ page }) => {
const longName = 'Extremely Long Product Name '.repeat(4).trim();
await page.route(PRODUCTS, async (route) => {
const response = await route.fetch(); // the real answer from ShopRung
const body = await response.json();
body.items[0].name = longName; // change one field
await route.fulfill({ response, json: body }); // everything else stays real
});
await page.goto('/');
await expect(page.getByTestId('product-card')).toHaveCount(12);
const card = page.getByTestId('product-card').first();
await expect(card.getByRole('heading', { name: longName })).toBeVisible();
await expect(card.getByRole('button')).toBeInViewport();
});
test('going offline shows an error, not a blank page', async ({ page }) => {
await page.route(PRODUCTS, (route) => route.abort('internetdisconnected'));
await page.goto('/');
await expect(page.getByTestId('error')).toBeVisible();
// ShopRung shows the browser's raw text here. Worth a bug report: say "You seem to be offline".
await expect(page.getByTestId('error')).toHaveText('Failed to fetch');
});
test('a slow API shows a loading state first', async ({ page }) => {
await page.route(PRODUCTS, async (route) => {
await new Promise((resolve) => setTimeout(resolve, 1500)); // hold the answer for 1.5 s
await route.continue();
});
await page.goto('/');
await expect(page.getByText('Loading…')).toBeVisible();
await expect(page.getByTestId('result-count')).toHaveText('12 products');
}); - Other codes:
failed,timedout,connectionrefused.line 38 - A finding, not a pass: raise it as a usability bug.line 42
- Hold the answer, then pass the real request on.line 47
- The loading state, normally gone in milliseconds.line 51
npx playwright test ✓ 4 [chromium] › tests/products-states.spec.ts:37:5 › going offline shows an error, not a blank page ✓ 5 [chromium] › tests/products-states.spec.ts:45:5 › a slow API shows a loading state first (2.0s) 5 passed (3.9s)
Spy on what the page sends
A route that does not change anything, only records the requests.
Routes can also watch. Create tests/spy.spec.ts: the handler records the q parameter of every product request, then route.continue() lets it through unchanged. The page loads (no search term, so ''), the user searches for MUG in capitals, and the test checks two things: the result (2 products, so search is not case sensitive) and what was sent (MUG, exactly as typed).
Spying is how you test that the UI sends the right request: the right filter, the right page number, no duplicate calls.
import { test, expect } from '@playwright/test';
test('search sends the exact term to the API', async ({ page }) => {
const seen: string[] = [];
await page.route('**/api/products?*', async (route) => {
seen.push(new URL(route.request().url()).searchParams.get('q') ?? '');
await route.continue(); // let the real request through
});
await page.goto('/');
await page.getByRole('searchbox', { name: 'Search products' }).fill('MUG');
await page.getByRole('searchbox', { name: 'Search products' }).press('Enter');
await expect(page.getByTestId('result-count')).toHaveText('2 products');
expect(seen).toEqual(['', 'MUG']);
}); - Read the query string of the intercepted request.line 6
- Nothing is mocked: the real request goes to ShopRung.line 7
- Exactly two requests: the page load, then the search.line 13
npx playwright test Running 6 tests using 1 worker ... 6 passed (4.3s)
Read a mocked request in the trace
See your fake response in the trace viewer, the way you would debug a failing mocked test.
Run one test with a trace, then open it. In the Network tab you see the request to /api/products?, and its response is the one your route sent (an empty list, or the 500). When a mocked test fails, this is the first place to look: did the route match, and what did it return?
npx playwright test -g "server error" --trace on
npx playwright show-report The report opens; click the test, then the trace, then Network.
Check it works
Mocked tests should still catch real bugs in the parts they do not mock. Switch on ShopRung's search-case bug (search becomes case sensitive) and run the suite: the spy test fails, because searching MUG finds nothing. The mocked tests keep passing: they control the answer, so a backend bug cannot reach them. That is exactly why a few unmocked tests must remain.
curl -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["search-case"]}'
npx playwright test 1) [chromium] › tests/spy.spec.ts:3:5 › search sends the exact term to the API
Error: expect(locator).toHaveText(expected) failed
Expected: "2 products"
Received: "0 products"
1 failed
5 passed Troubleshooting
The mock never applies.
Register the route before page.goto, and check the pattern: **/api/products?* needs the ?. Log route.request().url() to see the real URLs.
Another request is mocked by accident.
Your pattern is too broad. **/api/** catches everything, including login. Make it specific, or check route.request().method() inside the handler.
route.fetch hangs or fails.
ShopRung is not running: fetch sends the real request. Start it with npm start.
The slow test times out.
The delay is longer than the 5 second assertion timeout. Keep test delays short, or pass { timeout: 10_000 } to that one expect.
What changes in production
- Teams mock to test UI states (empty, errors, slow, odd data) and keep the happy path of critical journeys unmocked, so the real integration is still tested.
- Fake responses are copied from real ones and checked against the API's schema or contract, so mocks do not drift from what the backend really sends.
- For whole flows without a backend, teams record real traffic once to a HAR file and replay it with
page.routeFromHAR. - Usability findings like a raw "Failed to fetch" go into the bug tracker with the test as evidence, then the assertion is updated when the fix ships.
Interview angle
“How do you test UI error and edge states that are hard to reproduce?”
With network interception. In Playwright, page.route registered before navigation lets me fulfil an empty list or a 500, fetch the real response and change one field for edge data, abort requests to simulate going offline, delay them to see loading states, or just spy and check what the page sends. I keep mocks close to real responses, and I keep the critical journeys unmocked, because a mocked test cannot catch a backend bug.
Clean up
The full project
Every file from this lab, as it is after the last step.