Best Way to Intercept XHR Requests on a Page with Puppeteer and Return Mock Responses

Best Way to Intercept XHR Requests on a Page with Puppeteer and Return Mock Responses

21 May 2024 Stephan Petzl Leave a comment Tech-Help

Intercepting XHR requests and returning mock responses can be crucial for backendless testing of web applications. This guide will walk you through the process using Puppeteer, a Node library that provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol.

Step-by-Step Guide to Intercept and Mock XHR Requests

The key to intercepting XHR requests in Puppeteer is the request.respond() method. Below is a practical example:

Setup Request Interception

First, enable request interception on the page:


await page.setRequestInterception(true);

    

Intercept and Mock Responses

Next, use the page.on('request') event to intercept requests and provide mock responses:


page.on('request', request => {
    if (request.url() === 'https://example.com/api') {
        request.respond({
            content: 'application/json',
            headers: {"Access-Control-Allow-Origin": "*"},
            body: JSON.stringify({ key: 'mocked response' })
        });
    } else {
        request.continue();
    }
});

    

Explanation

  • Enable request interception with page.setRequestInterception(true).
  • Intercept each request using page.on('request').
  • Match the request URL to your target endpoint.
  • If matched, respond with mock data using request.respond().
  • Allow other requests to continue with request.continue().

Important Considerations

  • Ensure CORS headers are set correctly, or access to the mock data will be denied.
  • Mock data should be structured as expected by the application.

Advanced Library Options

For more advanced scenarios, you may consider using libraries such as puppeteer-request-intercepter or Mockiavelli. These libraries provide additional capabilities and integrations with testing frameworks.

Enhance Your Testing with Repeato

For those looking for a no-code solution to automate testing for iOS and Android apps, Repeato offers a highly efficient tool. Repeato uses computer vision and AI to create, run, and maintain automated tests. Its no-code interface and intuitive test recorder make it particularly fast to edit and run tests. For advanced users, Repeato also provides a scripting interface to automate complex use cases. Although primarily designed for mobile apps, Repeato already supports testing websites inside an Android emulator or device, with explicit web testing support coming soon.

Like this article? there’s more where that came from!