All challenges · Advanced Techniques
Challenge 22 of 29 · Stretch skills · Advanced Techniques
Intercept a Form POST
Intercept only the form submission, answer it yourself, and let every other request through untouched.
Skills you will practise
- routing by method
- route.continue
- stubbed responses
The concept
Often you want to fake one request without breaking the rest of the page. A form might POST to /api/contact, while the same URL also serves a GET, and the page needs its scripts, styles and other API calls to work normally.
A route handler receives every matching request. Inside it, route.request().method() tells you whether it is a GET, POST, PUT and so on. Fulfil the one you want to stub and call route.continue() for the rest so they reach the real server untouched. (route.fallback() is the alternative when you have several handlers and want the next one to decide.)
This keeps the mock surgical: you control the outcome of the submission without masking anything else.
The fragile version
const okResponse = { status: 200, json: { ok: true } };
await page.route('**/*', route => route.fulfill(okResponse));Why it breaks: This answers every request, including HTML, scripts and styles, with the same JSON, so the page breaks or tests something unrealistic.
A robust Playwright version
const created = { status: 201, json: { ok: true } };
await page.route('**/api/contact', route => {
if (route.request().method() !== 'POST') return route.continue();
return route.fulfill(created);
});
await page.getByRole('button', { name: 'Send' }).click();
await expect(page.getByText('Thanks, we will be in touch')).toBeVisible();Only the POST is stubbed; everything else behaves normally.
This is a general example on a made-up page, not the challenge’s reference solution.
Common mistakes
- Routing
**/*and fulfilling everything. - Leaving a branch where neither
fulfillnorcontinueis called. - Checking the method with the wrong case (
'post'instead of'POST').
FAQ
How do I mock only POST requests in Playwright?
Check route.request().method() in the handler and call route.continue() for other methods.
What is the difference between continue and fallback?
continue sends the request to the network; fallback passes it to the next matching route handler.
Can I modify the request instead of stubbing it?
Yes, route.continue({ postData, headers }).
Try it
Practise this in Challenge 22. You write the code in the browser editor with no setup. It runs in a fresh Chromium, a hidden validator checks what actually happened, and you get pass or fail, the logs and a video of the run. Create a free account to open the practice page and its hints. The reference solution and the hidden validator are shown only after you pass. We never publish solutions here.