Enable request interception, match the request you want to control, and call request.respond() with the status, content type, and body your test needs. Every other intercepted request must also be resolved—usually with request.continue()—or page activity can stall.
Mock a response with request interception
This example replaces one API response with JSON and lets all other requests proceed. The URL and response body are illustrative; change them to match the request and data your test expects.
As an Amazon Associate I earn from qualifying purchases.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
const targetUrl = 'https://example.test/api/data';
await page.setRequestInterception(true);
page.on('request', request => {
if (request.url() === targetUrl) {
return request.respond({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ ok: true, source: 'mock' }),
});
}
return request.continue();
});
await page.goto('https://example.test');
// Run assertions against the page or the UI that consumes the API response.
} finally {
await browser.close();
}
})();
page.setRequestInterception(true) must be enabled before the request you want to intercept occurs. request.respond() fulfills a matching intercepted request with the supplied response; the documented response fields include status, contentType, and body. The current API page reports Puppeteer 25.12.0; check the API documentation for your installed version if its signature or behavior differs.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Choose the request and response your test needs
Match precisely
Exact URL matching is a clear starting point, but it also requires the URL to match exactly. If the application adds query parameters or calls the same endpoint with different methods, make the condition reflect the request you intend to mock—for example, inspect request.method() and the URL. Avoid matching a broad substring unless every matching request should receive the same response.
#1 Best Overall
Return the test case
Use a success status and a body that exercises the UI state under test. For an error-path test, return an HTTP error status such as 404 or 503 with an appropriate body. That is still an HTTP response, not a transport failure: Puppeteer emits requestfinished for these HTTP error responses, rather than requestfailed.
Resolve every other request
With interception enabled, requests stall until they are continued, responded to, or aborted, except requests completed by the browser cache. The unmatched branch in the example calls request.continue(); omitting it can leave unrelated page requests waiting.
Rank #2
Make handlers safe when more than one listener is involved
A second listener or a package may resolve a request before your handler does. Resolving an already-handled request with abort(), continue(), or respond() can raise “Request is already handled!”. Check request.isInterceptResolutionHandled() before resolving it.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →page.on('request', request => {
if (request.isInterceptResolutionHandled()) return;
if (request.url() === targetUrl) {
return request.respond({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ ok: true }),
});
}
return request.continue();
});
If a handler awaits asynchronous work before resolving a request, check again after the await. Another handler may have acted in the meantime. Keep the final check and the call that resolves the request synchronous and adjacent.
When to use cooperative priorities
Puppeteer also documents Cooperative Intercept Mode for setups where multiple handlers intentionally participate in resolution. If every resolving handler supplies a numeric priority, handlers are awaited and the highest-priority resolution wins; equal-priority resolutions are ordered abort over respond over continue. If any handler omits a priority, legacy behavior applies and resolution may happen immediately. A single-handler mock usually does not need priorities.
Verify the mock and diagnose failures
Puppeteer emits request and response events by default. Use them to confirm that the expected request occurred and inspect the response received by the page. For HTTP 404 or 503 responses, look for requestfinished; reserve requestfailed for a failed request, such as a transport-level failure.
Rank #4
| Symptom | Likely cause | What to check |
|---|---|---|
| The page waits or navigation does not settle | An intercepted request was not resolved, or the handler did not match the intended request. | Ensure every branch calls respond(), continue(), or abort(); inspect the request URL and method. |
| “Request is already handled!” | Another handler or package already resolved the interception. | Check isInterceptResolutionHandled() immediately before resolution, and check again after any awaited work. |
| The page reports an API error despite a completed request | The mock returned an HTTP error status, which still completes as an HTTP response. | Inspect the response status and body; test transport failures separately if that is the behavior you need. |
| A data URL is not replaced | request.respond() on a data URL is documented as a no-op; mocking data URL requests is unsupported. |
Mock an interceptable network request instead. |
Performance and reliability considerations
- Install interception and its handler before triggering navigation or application actions that issue the target request.
- Keep matching conditions narrow so unrelated requests continue normally and the mock does not unintentionally affect other page behavior.
- Make mocked bodies deterministic and specific to the scenario; this makes failures easier to reproduce and assertions easier to interpret.
- Do not treat an HTTP error status as a network failure. The event distinction affects how tests should assert error paths.
Or skip the browser setup
ScreenshotNeo is for capturing a rendered website, not for mocking its network responses, so it does not replace the Puppeteer technique above. If your next task is obtaining a clean screenshot rather than controlling an API response, one request can capture a URL. See the ScreenshotNeo API documentation.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
ScreenshotNeo accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; those steps can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing, with page verdict and billing details returned in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.
Sign up for ScreenshotNeo free to try 1,000 screenshots a month without a card.
Best Value
Frequently Asked Questions
Can I use request.respond() without enabling interception?
No. Enable interception with page.setRequestInterception(true) before resolving requests with request.respond().
Does a mocked 404 trigger requestfailed?
No. An HTTP 404 or 503 response emits requestfinished; requestfailed indicates a request failure such as a transport-level failure.
Recommended Free Tools
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




