Mocking API Calls with Puppeteer’s Request Interception: A Practical Guide
Learn how to use Puppeteer’s request interception to mock API calls, speed up tests, and keep UI logic isolated. A concrete example, trade‑offs, and best‑practice checklist are included.
10 Aug 2026, 23:41 UTC

Problem: Unreliable Front‑End Tests Due to External APIs
When automating browser tests with Puppeteer, a common pain point is the dependency on live back‑end services. Network latency, intermittent failures, or data drift can make test runs flaky and slow. The question is: how can we isolate the UI from these external factors while still exercising real browser logic?
Thesis: Use Puppeteer’s Request Interception to Stub API Responses
Enabling page.setRequestInterception(true) lets you capture every outgoing request from the page and decide whether to abort, continue, or supply a custom response. By mocking the API layer, you gain deterministic data, faster execution, and the ability to test edge cases that would be hard to reproduce on a live server.
Setting Up Interception
Interception must be activated before the first navigation. The following snippet shows the minimal setup in a Node script that launches Chromium, opens a page, and intercepts requests.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Enable interception before navigation
await page.setRequestInterception(true);
page.on('request', (req) => {
// Handle request here
req.continue(); // default: let the request go through
});
await page.goto('https://example.com');
// … test logic …
await browser.close();
})();
Key points:
- Run the script with Node.js (≥12) and the
puppeteerpackage. - Only one
page.on('request')listener is needed per page. - Requests that are not explicitly handled must call
continue()orabort()to avoid hanging the page.
Example: Mocking a JSON API Endpoint
Assume the page fetches https://api.example.com/users/42 to display user details. We want to stub that call with a predictable JSON payload.
page.on('request', (req) => {
const url = req.url();
if (url.endsWith('/users/42')) {
const mockResponse = {
status: 200,
contentType: 'application/json',
body: JSON.stringify({
id: 42,
name: 'Alice',
email: '[contact removed]'
})
};
req.respond(mockResponse);
} else {
req.continue();
}
});
After navigation, the page will render the mocked user data. You can verify this with a simple assertion:
const displayedName = await page.$eval('#user-name', el => el.textContent);
if (displayedName !== 'Alice') throw new Error('Mock failed');
**Verification steps**:
- Run the test and confirm the UI shows “Alice”.
- Add
console.loginside the interception callback to ensure the request is captured. - Measure runtime with and without interception; you should see a measurable speed‑up for pages with many network calls.
Trade‑Offs and Limitations
| Aspect | Benefit | Risk / Caveat |
|---|---|---|
| Determinism | Consistent data for every run. | May mask real API failures. |
| Performance | Fewer network round‑trips. | Callback overhead can slow large pages. |
| Complexity | Fine‑grained control over headers, redirects. | Requires careful handling of all non‑mocked requests. |
| Browser Compatibility | Works in Chromium‑based browsers. | Behavior may differ in Edge or Chrome on mobile. |
Because interception runs in Node’s event loop, heavy processing inside the callback can block the browser, leading to timeouts. Keep logic lightweight or delegate heavy work to asynchronous functions.
Actionable Takeaways
- Always enable interception before the first
page.goto()to avoid missing early requests. - Use
req.respond()only for the endpoints you truly want to mock; let others continue. - Log the URLs intercepted during a test run to verify coverage and catch missing mocks.
- When stubbing many endpoints, consider grouping them into a simple mapping object to keep the code maintainable.
- Run a parallel “real‑network” test occasionally to catch connectivity regressions.
By integrating request interception into your Puppeteer test suite, you can achieve faster, more reliable UI tests while still exercising real browser behavior. Just remember to balance mocking with genuine network checks to maintain overall test quality.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.