Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

How to Mock Network Responses in Puppeteer

Use Puppeteer request interception to return a controlled response, continue unmatched requests, and avoid conflicts when multiple handlers are active.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.