# Speed Up Your Playwright Scripts with Request Interception

> Discover Playwright's request interception feature to control network interactions, mock responses, modify real responses, or simulate errors.

Source: https://www.checklyhq.com/blog/speed-up-playwright-scripts-request-interception/

---

[Blog](https://www.checklyhq.com/blog/) / [Checkly Community](https://www.checklyhq.com/blog/tag/community/) / [Playwright](https://www.checklyhq.com/blog/tag/playwright/)

# Speed Up Your Playwright Scripts with Request Interception

[Nočnica Mellifera](https://www.checklyhq.com/blog/author/nica-mellifera/)

March 15, 2024 · Updated July 2, 2024

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](https://www.youtube.com/c/ChecklyHQ) 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](https://join.slack.com/t/checklycommunity/shared_invite/zt-1gvia8904-_XrzM3ul3vS3YNoKie5tbw) to talk about better ways to test your site!

[Nočnica Mellifera](https://www.checklyhq.com/blog/author/nica-mellifera/)

Developer Advocate

Nočnica Mellifera (She/Her) was a developer for seven years before moving into developer relations. She specializes in containerized workloads, serverless, and public cloud engineering. Nočnica has long been an advocate for open standards, and has given talks and workshops on OpenTelemetry and Kubernetes architecture. She enjoys making music that friends have described as "unlistenable." In her spare time she cares for her two children and hundreds of houseplants.

In This Article

- The Setup
- The Problem
- The Solution: Request Interception
- Request interception for faster, sleeker site monitoring
- Advanced Techniques in Request Interception with Playwright
- Conclusion: request interception for in-depth test hacking
- Join the Checkly Community!

Monitor with AI

Let your agents create & deploy monitors with deep understanding of your application

[Start for free](https://app.checklyhq.com/signup)

Share on social

Try Checkly

## Catch it before your users do

Run Playwright and API checks against production every minute, from locations around the world. Your checks live in your repo and deploy with your code.

[Start for free](https://app.checklyhq.com/signup) [Book a demo](https://www.checklyhq.com/demo-request/)

Free plan. No credit card.

# scaffold a project with example checks

$ npm create checkly@latest

# run them from our global locations

$ npx checkly test

# turn them into production monitors

$ npx checkly deploy

## Related Articles

[Running Your Playwright Tests in Parallel or in Sequence March 16, 2024](https://www.checklyhq.com/blog/running-your-playwright-tests-in-parallel-or-in-se/)[Playwright Locators: Why Use Page Locators to Select Elements June 1, 2023](https://www.checklyhq.com/blog/understanding-element-handles-and-page-locators/)[Avoid Delays and "waitFor" Statements Using Playwright Auto-Waiting June 14, 2023](https://www.checklyhq.com/blog/playwright-auto-waiting/)
