End-to-End Tests With Playwright: Frontend, Backend and Database · Part 7 of 14 in the series
Part 7: Testing the Frontend
Test the page in a real browser while the test plays the API: a page object, a guard against requests nobody mocked, and twelve tests for states a real backend rarely shows, from loading to unreachable.
End-to-End Tests With Playwright: Frontend, Backend and DatabasePart 7 of 14
On this page
Quest objectives
- Understand why the frontend section mocks the API, and where the limit of that is
- Write a page object, so tests read like sentences and a renamed label is changed once
- Answer API requests from the test with page.route, and make every unmocked request fail
- Hold an answer back to test the loading state, and let the API fail and recover
- Check what the page sends to the API, not only what it shows
The backend section of the last part sends requests to the real API and looks into the real database. This part turns to the other side of the app: the page in the browser. The question here is a different one. Not "does the API work?", but "does the page do the right thing with whatever the API says?"
For that question a real API gets in the way. It answers within milliseconds, so the loading text is gone before a test can look. It works, so the error message never shows. That is why the tests of this section mock the API: every answer the page gets comes from the test itself. A test can then say anything: a full list, an empty one, a slow answer, a broken one, none at all.
You have seen the tool for it in part 3: page.route, with one test and one made-up answer. This part turns that single test into a section: a page object, fixtures of the frontend's own, and twelve tests in two files.
A page object
Every test that drives the browser has to find the same things on the page: the field for the title, the button, the list. If each test writes these locators itself, a renamed label means changing them all. A page object solves that: a class that knows where things are on the page and how to use them. It is the one place to change, and tests that use it read almost like sentences. Create tests/support/board.ts:
import type { Locator, Page } from '@playwright/test';
/** The quest board as a visitor sees it: where things are on the page, and how to use them. */
export class QuestBoard {
readonly page: Page;
readonly title: Locator;
readonly reward: Locator;
readonly addButton: Locator;
readonly quests: Locator;
readonly problem: Locator;
constructor(page: Page) {
this.page = page;
this.title = page.getByLabel('New quest');
this.reward = page.getByPlaceholder('Reward');
this.addButton = page.getByRole('button', { name: 'Add quest' });
this.quests = page.getByRole('list', { name: 'Quests' }).getByRole('listitem');
this.problem = page.getByRole('alert');
}
async open() {
await this.page.goto('/');
}
async add(title: string, reward?: number) {
await this.title.fill(title);
if (reward !== undefined) await this.reward.fill(String(reward));
await this.addButton.click();
}
/** The checkbox that marks a quest as done. */
checkbox(title: string) {
return this.page.getByRole('checkbox', { name: title });
}
deleteButton(title: string) {
return this.page.getByRole('button', { name: `Delete ${title}` });
}
}The file lies in tests/support and not beside the frontend tests, because the end-to-end tests of the next part will use it too.
The constructor builds one locator for each thing on the page. Remember from part 2 that a locator is a description of how to find something, not the thing itself. Locators are lazy: creating one looks at nothing. Only when a test uses it, to click or to check, does Playwright search the page, and it searches again every time. That is why the constructor can set them all up before the page is even open.
quests is a chain: first the list named "Quests" (the aria-label of the <ul>), then the list items inside it. problem finds whatever has the role alert, which both the message under the form and the box for a failed load have.
open and add are what a visitor does. add fills in the reward only if you pass one, so a test can also leave the field at its default. checkbox and deleteButton are methods because they depend on a quest: the checkbox is named after the quest's title, because one label wraps them both, and the button's name is "Delete" plus the title.
One line stands out: getByPlaceholder('Reward'). Everything else is found the way a person finds it: by a label, a role, a name. The reward field has no label, so its placeholder is all the page object can hold on to. Leave it for now. Part 12 comes back to this line.
Fixtures for the frontend
The frontend tests get a test function of their own. The one in tests/fixtures.ts would be the wrong choice. Its db fixture has run for every test since the last part, so every worker would copy the template into a database of its own. And page reads baseURL, which comes from server there, so every worker would start the app as well. No frontend test ever talks to either. Create tests/frontend/fixtures.ts:
import { test as base, type Page } from '@playwright/test';
import type { Quest } from '../../web/src/api.ts';
import { QuestBoard } from '../support/board.ts';
export const SWORD: Quest = {
id: 1,
title: 'Find the lost sword',
reward: 50,
done: false,
createdAt: '2026-01-01T10:00:00.000Z',
};
export const DRAGON: Quest = {
id: 2,
title: 'Feed the dragon',
reward: 10,
done: true,
createdAt: '2026-01-01T11:00:00.000Z',
};
type Answer = { status?: number; json?: unknown };
/**
* Answers one kind of request to the API, such as `POST /quests`, in place of the real API.
* Requests with another method are passed on to the routes that were set up before.
*/
export async function mockApi(page: Page, method: string, path: string, answer: Answer) {
await page.route(`**/api${path}`, (route) =>
route.request().method() === method ? route.fulfill(answer) : route.fallback(),
);
}
export const test = base.extend<{ board: QuestBoard }>({
// A request to the API that a test has not mocked goes nowhere, and never to a real server.
page: async ({ page }, use) => {
await page.route('**/api/**', (route) => route.abort());
await use(page);
},
board: async ({ page }, use) => {
await use(new QuestBoard(page));
},
});
export { expect } from '@playwright/test';The test data. SWORD and DRAGON are two quests as the API would send them. They are typed with Quest, the interface the frontend itself uses in web/src/api.ts. If that type ever changes, TypeScript complains about the test data too.
mockApi. page.route takes a pattern and a function. Every request of the page whose address fits the pattern goes to that function instead of the network. The two stars at the start of the pattern stand for anything, so host and port do not matter. The function looks at the request's method. If it is the one the test named, route.fulfill answers the request on the spot, with the status and the JSON from answer (the status is 200 if you name none). If not, route.fallback() passes the request on to the next route that fits.
"Next" has a precise meaning: when several routes fit a request, Playwright asks them newest first. So a test can mock GET /quests and after it POST /quests. A GET comes to the newer route first, which declines, and the older one answers.
The page fixture. A fixture can be replaced under its own name. This one takes Playwright's page, adds one route to it and hands it on. The route fits every request to /api/ and aborts it. Because it is set up before the body of the test runs, it is the oldest route and is asked last: it only gets what no mock of the test has answered. Such a request fails, as if the server were gone.
Why so strict? The frontend's dev server passes /api on to port 3000, as you set it up in part 1, and your development API may well be running there. Without the catch-all, a request you forgot to mock would quietly fetch real data from your development database, and the test would pass or fail depending on what happens to be in it. With it, a forgotten mock shows up at once, as an error in the page. It is the lesson of part 2 again: a test must not depend on anything it did not set up itself.
board. The last fixture builds the page object from the test's page. A test asks for board in its arguments and has the whole board at hand.
The states of the board
Now the tests. Replace the contents of tests/frontend/board.spec.ts from part 3:
import { DRAGON, SWORD, expect, mockApi, test } from './fixtures.ts';
test('lists the quests the API sends', async ({ page, board }) => {
await mockApi(page, 'GET', '/quests', { json: [SWORD, DRAGON] });
await board.open();
await expect(board.quests).toHaveText([/Find the lost sword.*50 gold/, /Feed the dragon.*10 gold/]);
await expect(board.checkbox('Find the lost sword')).not.toBeChecked();
await expect(board.checkbox('Feed the dragon')).toBeChecked();
await expect(page.getByText('1 of 2 quests open')).toBeVisible();
});
test('invites to add the first quest when there is none', async ({ page, board }) => {
await mockApi(page, 'GET', '/quests', { json: [] });
await board.open();
await expect(page.getByText('No quests yet. Add the first one!')).toBeVisible();
await expect(board.quests).toHaveCount(0);
});
test('says that it is loading until the API answers', async ({ page, board }) => {
// The answer waits until the test lets it go.
const answer = Promise.withResolvers<void>();
await page.route('**/api/quests', async (route) => {
await answer.promise;
await route.fulfill({ json: [SWORD] });
});
await board.open();
await expect(page.getByText('Loading quests…')).toBeVisible();
answer.resolve();
await expect(page.getByText('Loading quests…')).toBeHidden();
await expect(board.quests).toHaveCount(1);
});
test('offers to try again when the API fails', async ({ page, board }) => {
await mockApi(page, 'GET', '/quests', { status: 500, json: { error: 'Out of mana.' } });
await board.open();
await expect(board.problem).toContainText('The quests could not be loaded.');
// The API recovers: of two routes for the same request, the newer one wins.
await mockApi(page, 'GET', '/quests', { json: [SWORD] });
await page.getByRole('button', { name: 'Try again' }).click();
await expect(board.quests).toHaveText([/Find the lost sword/]);
await expect(board.problem).toBeHidden();
});
test('shows the same message when the API cannot be reached', async ({ page, board }) => {
await page.route('**/api/quests', (route) => route.abort());
await board.open();
await expect(board.problem).toContainText('The quests could not be loaded.');
});
test('marks a quest as done', async ({ page, board }) => {
await mockApi(page, 'GET', '/quests', { json: [SWORD] });
await mockApi(page, 'PATCH', '/quests/1', { json: { ...SWORD, done: true } });
await board.open();
const request = page.waitForRequest((request) => request.method() === 'PATCH');
await board.checkbox('Find the lost sword').check();
expect((await request).postDataJSON()).toEqual({ done: true });
await expect(page.getByText('0 of 1 quests open')).toBeVisible();
});
test('removes a deleted quest from the list', async ({ page, board }) => {
await mockApi(page, 'GET', '/quests', { json: [SWORD, DRAGON] });
await mockApi(page, 'DELETE', '/quests/2', { status: 204 });
await board.open();
const request = page.waitForRequest((request) => request.method() === 'DELETE');
await board.deleteButton('Feed the dragon').click();
expect((await request).url()).toMatch(/\/api\/quests\/2$/);
await expect(board.quests).toHaveText([/Find the lost sword/]);
});
test('keeps the quest and says why when a change fails', async ({ page, board }) => {
await mockApi(page, 'GET', '/quests', { json: [SWORD] });
await mockApi(page, 'DELETE', '/quests/1', { status: 404, json: { error: 'There is no such quest.' } });
await board.open();
await board.deleteButton('Find the lost sword').click();
await expect(board.problem).toHaveText('There is no such quest.');
await expect(board.quests).toHaveCount(1);
});The first two tests are the plain cases: a list and an empty board. toHaveText with a list checks every item and their order, as in part 3. The pattern /Find the lost sword.*50 gold/ makes sure that title and reward stand in the same row.
Loading. A real API shows this state for a few milliseconds. Here the test holds it for as long as it likes. Promise.withResolvers() returns a promise together with the function that resolves it. The route waits for that promise before it answers, so the page keeps saying "Loading quests…" until the test calls answer.resolve(). The test looks, lets the answer go, and checks that the text gives way to the list. There is no sleep anywhere: the test does not guess how long loading takes, it decides.
Failing and recovering. The fourth test first answers with status 500 and expects the alert. Then it mocks the same request a second time, now with a list. The newer route wins, so the click on "Try again" gets the good answer: the list appears and the alert is gone. The fifth test uses route.abort(): the request fails without any answer, as it does when a server is down. The catch-all of the fixture would do the same, but written out, the test says what it is about.
What the page sends. With a mock, a test sees both directions: what the page shows and what it tells the API. page.waitForRequest returns a promise for the next request that meets the condition. Note the order: the waiting starts before the click and is awaited after it. Started after the click, it could miss a request that has already left. postDataJSON() is the body the page sent, and the test expects exactly { done: true }. The delete test checks the address instead: the request has to go to quest 2 and to no other.
The last test is the unhappy end of a change: the API answers a delete with 404 and a sentence. The page has to show that sentence and keep the quest in the list.
The form
The form gets a file of its own, tests/frontend/form.spec.ts:
import { DRAGON, SWORD, expect, mockApi, test } from './fixtures.ts';
test('sends a new quest to the API and shows it', async ({ page, board }) => {
await mockApi(page, 'GET', '/quests', { json: [DRAGON] });
await mockApi(page, 'POST', '/quests', { status: 201, json: SWORD });
await board.open();
const request = page.waitForRequest((request) => request.method() === 'POST');
await board.add('Find the lost sword', 50);
expect((await request).postDataJSON()).toEqual({ title: 'Find the lost sword', reward: 50 });
await expect(board.quests).toHaveText([/Feed the dragon/, /Find the lost sword.*50 gold/]);
// The form is ready for the next quest.
await expect(board.title).toHaveValue('');
await expect(board.reward).toHaveValue('10');
});
test('removes spaces around the title', async ({ page, board }) => {
await mockApi(page, 'GET', '/quests', { json: [] });
await mockApi(page, 'POST', '/quests', { status: 201, json: SWORD });
await board.open();
const request = page.waitForRequest((request) => request.method() === 'POST');
await board.add(' Find the lost sword ');
expect((await request).postDataJSON()).toEqual({ title: 'Find the lost sword', reward: 10 });
});
test('shows what the API says when it turns a quest down', async ({ page, board }) => {
await mockApi(page, 'GET', '/quests', { json: [SWORD] });
await mockApi(page, 'POST', '/quests', {
status: 409,
json: { error: 'A quest with this title already exists.' },
});
await board.open();
await board.add('Find the lost sword');
await expect(board.problem).toHaveText('A quest with this title already exists.');
await expect(board.quests).toHaveCount(1);
// What was typed stays, so it can be corrected.
await expect(board.title).toHaveValue('Find the lost sword');
});
test('does not send a quest without a title', async ({ page, board }) => {
await mockApi(page, 'GET', '/quests', { json: [] });
const posts: string[] = [];
page.on('request', (request) => {
if (request.method() === 'POST') posts.push(request.url());
});
await board.open();
await board.addButton.click();
// The browser stops the form and points at the field that is missing.
await expect(board.title).toBeFocused();
expect(posts).toEqual([]);
});The first test follows a new quest all the way: the body of the request (with the reward as a number, not as text), the new row at the end of the list, and the form back at an empty title and a reward of 10. The second types spaces around the title and expects that they never reach the API. The third lets the API turn the quest down with 409: the page shows the API's sentence, the list stays as it was, and what was typed stays in the field, so it can be corrected.
The fourth test is about something that must not happen. The title field is required, so the browser itself refuses to submit an empty form and puts the cursor into the field. There is no request to wait for, so the test listens: page.on('request', …) notes every POST the page sends, and at the end that list has to be empty. The line before it matters: toBeFocused() waits until the browser has reacted to the click. Without it, "no POST so far" could mean no more than that the test looked too early.
Run the section
Run the frontend project on its own:
$ npm run test:frontend> questboard@1.0.0 test:frontend> playwright test --project=frontendRunning 12 tests using 8 workers ✓ 2 [frontend] › tests/frontend/board.spec.ts:14:1 › invites to add the first quest when there is none (295ms) ✓ 8 [frontend] › tests/frontend/board.spec.ts:53:1 › shows the same message when the API cannot be reached (232ms) ✓ 4 [frontend] › tests/frontend/board.spec.ts:3:1 › lists the quests the API sends (269ms) ✓ 6 [frontend] › tests/frontend/board.spec.ts:23:1 › says that it is loading until the API answers (271ms) ✓ 5 [frontend] › tests/frontend/board.spec.ts:73:1 › removes a deleted quest from the list (307ms) ✓ 1 [frontend] › tests/frontend/board.spec.ts:39:1 › offers to try again when the API fails (341ms) ✓ 3 [frontend] › tests/frontend/board.spec.ts:61:1 › marks a quest as done (337ms) ✓ 7 [frontend] › tests/frontend/board.spec.ts:85:1 › keeps the quest and says why when a change fails (306ms) ✓ 10 [frontend] › tests/frontend/form.spec.ts:18:1 › removes spaces around the title (178ms) ✓ 12 [frontend] › tests/frontend/form.spec.ts:45:1 › does not send a quest without a title (171ms) ✓ 11 [frontend] › tests/frontend/form.spec.ts:29:1 › shows what the API says when it turns a quest down (219ms) ✓ 9 [frontend] › tests/frontend/form.spec.ts:3:1 › sends a new quest to the API and shows it (234ms) 12 passed (2.3s)
Twelve tests in a little over two seconds, and no [setup] line above them: this section needs neither the template database nor an API. For now the pages still come from the Vite dev server that Playwright starts. The next part changes that.
What you have now
The frontend section is filled: twelve tests that put the board into its states, including the ones a real backend rarely shows, and that check what the page sends as well as what it shows. A page object keeps the knowledge about the page in one place, and a catch-all route makes sure that no test reaches a real server by accident.
What is still missing is the proof that page, API and database fit together. In the next part everything is real: the end-to-end tests drive a browser against each worker's own server and database, and the page object comes along.
Comments
The comments are GitHub Discussions: sign in with GitHub to write one.
The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.