(Updated: )

Speed Up Your Playwright Scripts with Request Interception

Share on social

A title screen for a blog on request interception. Image of a football interception By Torsten Bolten, AFpix.de - Self-photographed, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=3158515
Table of contents

With end-to-end testing, efficiency is key. Every millisecond counts, especially when you're running a large suite of tests. Today, we'll dive into how you can use request interception in Playwright to significantly reduce the runtime of your scripts.

The Setup

Imagine a simple Playwright script: it launches a headless Chromium browser, navigates to a website, and captures a screenshot. This operation, while straightforward, takes about two seconds to complete. For a single test, this might seem inconsequential. However, when scaled to dozens or hundreds of tests daily, the cumulative delay becomes a critical concern.

The Problem

The root of the delay lies in the network layer. A typical website loads various resources: stylesheets, scripts, images, and fonts. But consider a test scenario like verifying a login flow. Do you need all these resources? The answer is a resounding no.

The Solution: Request Interception

Request interception is your silver bullet. Playwright offers the page.route function, allowing you to intercept and abort unnecessary network requests. By specifying patterns for the requests you want to block, you can prevent the loading of non-essential resources such as images, CSS, or analytics scripts.

Implementing Request Interception

Listen for Requests: First, attach an event listener to log request URLs. This step helps you identify which requests are essential and which are not.

Block Unnecessary Requests: Use page.route to match and abort unwanted requests. For instance, to block images, you might write:

page.route('**/*.{png,jpg,jpeg}', route => route.abort());

Refine Your Blocking Strategy: You can add multiple page.route calls to block various resource types, further streamlining your test execution.

The Impact

After implementing request interception, the loading time of the website in our test scenario dropped by 500 milliseconds. This improvement is substantial, demonstrating the power of request interception in optimizing test performance.

Request interception for faster, sleeker site monitoring

Request interception enables faster test execution by eliminating unnecessary network traffic. By carefully selecting which resources to load, you can achieve more efficient, speedier test runs. This technique is particularly valuable in continuous integration environments, where every second saved accelerates the development cycle.

Remember, in testing as in development, efficiency is not just about doing things faster but doing them smarter. If your big concern is errors or delays in loading resources, request interception can hide those problems.

For a bit more detail, on the Checkly YouTube channel Stefan’s got a great demonstration:

Advanced Techniques in Request Interception with Playwright

Beyond the basics of speeding up your Playwright scripts through request interception, there's a wealth of advanced strategies that can further refine your testing process. These techniques not only enhance performance but also allow for more nuanced testing scenarios, including error handling and response manipulation.

Mocking Responses for Edge Case Testing

Sometimes during testing, requesting a response from an external services is impractical or slow. Here, request interception lets you mock responses directly within your tests.

How to Mock a Response

Playwright's page.route method intercepts requests, allowing you to provide custom responses. For example, to mock a response from an API endpoint, you could use:

await page.route('https://api.openweathermap.org/data/2.5/weather?lat=44.34&lon=10.99&appid={API key}', route => {
    route.fulfill({
        body: JSON.stringify([{ name: 'Mocked Post' }]),
    });
});

This approach ensures your test environment is both controlled and predictable, essential for testing specific application behaviors without relying on external services.

Simulating HTTP Errors

Testing how your application handles errors is just as crucial as testing its success paths. By intercepting requests, you can simulate various error conditions to ensure your application responds appropriately.

Mocking an HTTP Error

To simulate an error, use the route.abort() method. This method stops the request, mimicking network errors or server issues:

await page.route('https://pro.openweathermap.org/data/2.5/forecast/hourly?lat=44.34&lon=10.99&appid={API key}', route => {
    route.abort();
});

If you expect a page to fail gracefully when an external service is down, this is one way to test that.

Modifying Real Responses

A hybrid approach involves intercepting a real request, modifying its response, and then proceeding with the test. This method is particularly useful for creating edge cases without extensive setup or for augmenting real data with test-specific conditions.

How to Modify a Real Response

First, make the original request within the page.route callback, then modify the response before fulfilling the route:

await page.route(
    'https://pro.openweathermap.org/data/2.5/forecast/hourly?lat=44.34&lon=10.99&appid={API key}',
    async (route) => {
        const response = await route.fetch(); // Make the original request
        const result = await response.json(); // Get the response

        // Modify the response
        const modifiedResult = result.map(list => ({ ...list, weather: `${weather.main} (Modified)` }));

        route.fulfill({ json: modifiedResult });
    }
);

This approach offers the best of both worlds: testing against real data while still having the flexibility to introduce test-specific modifications.

Conclusion: request interception for in-depth test hacking

Request interception in Playwright is a powerful feature that extends beyond merely speeding up tests by blocking unnecessary resources. It enables precise control over the network interactions of your tests, allowing for detailed testing of application behavior under various conditions. Whether you're mocking responses, simulating errors, or modifying real responses, Playwright provides the tools necessary to create a robust and comprehensive test suite.

Join the Checkly Community!

Checkly, the best choice for running synthetic user tests as automated service monitors, has a whole team of people passionate about Playwright. We’d love you to join us on the Checkly Slack to talk about better ways to test your site!

Share on social