I’ve been thinking about testing lately. Not just any testing, but the kind that truly reflects how users experience our applications. We build these complex systems where a single button click can trigger a cascade of API calls, state changes, and UI updates. Traditional testing often feels like examining individual gears in a clock without seeing if the whole thing tells the correct time. That’s what led me to explore a particular combination of tools.
Consider this: what if you could watch every conversation between your frontend and backend during a test? Not just watch, but gently guide those conversations to test specific outcomes? This is where Playwright and Axios interceptors come together.
Playwright gives us a powerful way to automate browsers. It lets us write scripts that click buttons, fill forms, and navigate pages just like a real user would. It’s excellent for testing the visual and interactive layer of an application. But modern web applications are more than just what happens in the browser. They’re in constant dialogue with servers.
This is where Axios, a popular HTTP client, enters the picture. Many applications use it to handle API calls. Axios has a feature called interceptors, which are functions you can attach to run before a request is sent or after a response is received. They act as checkpoints.
Now, imagine combining these two. We use Playwright to drive the browser—the user’s perspective. Simultaneously, we use Axios interceptors to monitor and, when needed, alter the network traffic flowing between the application and its backend. This combination creates a testing environment with unprecedented control.
Why is this control so valuable? Think about testing an error state. Maybe you need to see how your app behaves when a payment API returns a “card declined” message. With a real backend, reproducing this reliably is a challenge. You’d need to configure test data or mock an entire service. But with an interceptor, you can simply catch the request to the payment endpoint and return a custom error response. The frontend receives this mock response and reacts, allowing you to test the UI’s error handling logic instantly and deterministically.
The setup is more straightforward than it might sound. You start with a standard Playwright test. Then, you inject a script into the browser context that modifies the Axios instance your application uses. This script adds the interceptors. Because Playwright lets us execute code within the page context, we can reach into the application’s runtime and adjust its behavior for our test.
Here’s a basic look at how you might structure this. First, a simple Playwright test skeleton:
const { test, expect } = require('@playwright/test');
test('test checkout with mocked failure', async ({ page }) => {
// We will inject our interceptor logic here
await page.goto('https://my-app.com/checkout');
// ... rest of the test
});
The magic happens in the injection. Before navigating to the page, we can add an initialization script to the browser context. This script will attach an interceptor to Axios.
await page.addInitScript(() => {
// This code runs inside the browser page
if (window.axios) {
window.axios.interceptors.response.use(
(response) => {
// Let normal responses pass through
return response;
},
(error) => {
// Intercept errors
const url = error.config?.url;
// Mock a specific API failure
if (url && url.includes('/api/payment/process')) {
console.log('Intercepting payment call for testing.');
// Return a mocked error response
return Promise.reject({
response: {
status: 402,
data: { message: 'Card declined' }
}
});
}
// For all other errors, proceed as normal
return Promise.reject(error);
}
);
}
});
This script waits for the page to load, finds the Axios instance, and adds a response interceptor. When the application tries to call the payment endpoint, our interceptor jumps in, blocks the real network call, and immediately returns a fabricated error. The application code then handles this error as if it came from the real server.
What kind of scenarios does this open up? Beyond error handling, you can test loading states by simulating slow network responses. You can verify that your app sends the correct authentication tokens by inspecting request headers. You can even provide mock data for lists and forms, making your tests run faster by avoiding database queries.
This approach shines in continuous integration pipelines. Tests become more reliable because they don’t depend on the availability or specific state of external services. They run faster because there’s no network latency. A test suite that might have taken minutes can now run in seconds, providing quicker feedback to developers.
It also encourages better testing practices. Instead of just checking if a button turns green, you can write tests that assert: “When the user submits the form, an API call with these specific parameters is made, and upon receiving a success response, the UI shows a confirmation message.” You’re testing the entire workflow, not just the starting and ending points.
Does this mean we should mock every API call? Not at all. The goal isn’t to isolate the frontend completely. End-to-end tests with real backend integrations are still crucial for validating the fully assembled system. This technique is a complementary tool. It’s for those specific, hard-to-reach corners of application logic—the error flows, the edge cases, the timeout handling—that are risky but expensive to test with full infrastructure.
In practice, I’ve found this blend makes my tests more expressive. I can write a test called “shows error banner when inventory API is unavailable” and know that test will consistently create that exact condition. It turns unpredictable, flaky tests into reliable, fast-executing specifications of behavior.
The integration does require that your application uses Axios in a way that’s accessible from the window object, which is common in many setups. It’s a small architectural consideration for a significant gain in test quality.
So, we start with a user action simulated by Playwright. We layer in control over the network layer via Axios. The result is a test that understands both the “what” the user does and the “how” the application responds internally. It bridges two worlds, giving us a clearer picture of application health.
I encourage you to try blending these tools in your next test suite. Start with a single complex user journey that depends on an API. Use an interceptor to guarantee the API’s response, and watch how much more confident you become in that test’s result. It turns testing from a chore into a powerful design tool.
If you’ve experimented with similar patterns or have questions about specific implementation challenges, I’d love to hear about it in the comments below. Sharing different approaches helps us all build more robust software. If you found this perspective useful, please consider liking or sharing this article with others in your team who might be wrestling with the same testing challenges.
As a best-selling author, I invite you to explore my books on Amazon. Don’t forget to follow me on Medium and show your support. Thank you! Your support means the world!
101 Books
101 Books is an AI-driven publishing company co-founded by author Aarav Joshi. By leveraging advanced AI technology, we keep our publishing costs incredibly low—some books are priced as low as $4—making quality knowledge accessible to everyone.
Check out our book Golang Clean Code available on Amazon.
Stay tuned for updates and exciting news. When shopping for books, search for Aarav Joshi to find more of our titles. Use the provided link to enjoy special discounts!
📘 Checkout my latest ebook for free on my channel!
Be sure to like, share, comment, and subscribe to the channel!
Our Creations
Be sure to check out our creations:
Investor Central | Investor Central Spanish | Investor Central German | Smart Living | Epochs & Echoes | Puzzling Mysteries | Hindutva | Elite Dev | JS Schools
We are on Medium
Tech Koala Insights | Epochs & Echoes World | Investor Central Medium | Puzzling Mysteries Medium | Science & Epochs Medium | Modern Hindutva