intercepts (Test Automation)
Learn intercepts (Test Automation) step by step with clear examples and exercises.
Title: Test Automation with JavaScript: Intercepts (Cypress, Selenium, Playwright)
Why This Matters
In test automation, intercepting network requests and responses is a powerful technique to control, manipulate, or verify HTTP/HTTPS traffic during your tests. Intercepts allow you to stub responses, modify requests, and even spy on real-time data flow. By understanding how to use intercepts in popular test automation frameworks like Cypress, Selenium (WebDriver), and Playwright, you'll be able to write more robust and efficient tests, saving time and effort during development cycles.
Prerequisites
To follow this lesson, you should have a basic understanding of:
- JavaScript programming language
- Test automation fundamentals (e.g., writing test cases, assertions)
- Familiarity with one or more test automation frameworks such as Cypress, Selenium, and Playwright
Core Concept
Intercepting network requests in test automation involves setting up a proxy server that intercepts incoming and outgoing HTTP/HTTPS traffic. The test automation framework allows you to manipulate these intercepted requests and responses based on specific conditions or rules. In this lesson, we will focus on using intercepts with Cypress, Selenium (WebDriver), and Playwright.
Intercepting Network Requests in Cypress
Cypress provides the cy.intercept() function to spy, stub, and modify network requests. Here's a basic example:
describe('Intercept Example', () => {
it('Intercept a request', () => {
cy.intercept('/example-endpoint', (req) => {
// Modify the request here if needed
req.url = 'http://new-example-endpoint';
// Respond with a static response
const fakeResponse = { body: 'Hello from intercept!' };
req.reply(fakeResponse);
});
cy.visit('http://your-test-app.com');
cy.contains('Hello from intercept!').should('be.visible');
});
});
In this example, we're intercepting requests to /example-endpoint. We modify the request URL and respond with a static response containing 'Hello from intercept!'. After visiting the test app, we verify that the content appears on the page.
Intercepting Network Requests in Selenium (WebDriver)
Selenium doesn't have built-in support for intercepting network requests like Cypress. However, you can use external libraries such as webdriverio-proxy or selenium-wire to achieve this functionality. Here's an example using webdriverio-proxy:
const { Builder, build, Capabilities } = require('selenium-webdriver');
const { Proxy, ManualProxyConfigurator } = require('selenium-webdriver/lib/proxy');
const proxy = new Proxy();
proxy.manualConfiguration(new ManualProxyConfigurator({
httpProxy: 'localhost:8080', // Your proxy server port
sslProxy: 'localhost:8080', // SSL traffic will be routed through the same proxy
proxyType: Proxy.MANUAL,
}));
const driver = new Builder()
.withCapabilities(Capabilities.chrome())
.setProxy(proxy)
.build();
// Your test code here using `driver` instance
In this example, we set up a manual proxy server and configure Selenium to use it for all network traffic. You can then use tools like MITMProxy or Charles Proxy to intercept requests and manipulate responses as needed.
Intercepting Network Requests in Playwright
Playwright also provides the intercept() function for network request interception:
const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
// Intercept requests to /example-endpoint
await page.route('/example-endpoint', (route, request) => {
// Modify the request here if needed
route.request().setHeader('custom-header', 'test-value');
// Respond with a static response
const fakeResponse = JSON.stringify({ body: 'Hello from Playwright!' });
route.respond({ status: 200, contentType: 'application/json', body: fakeResponse });
});
await page.goto('http://your-test-app.com');
const content = await page.$eval('#content', (el) => el.textContent);
console.log(content); // Outputs: Hello from Playwright!
await browser.close();
})();
In this example, we intercept requests to /example-endpoint, modify the request header, and respond with a static JSON response containing 'Hello from Playwright!'. After navigating to the test app, we extract the content of an element and verify that it matches our expected response.
Worked Example
Let's create a worked example using Cypress:
- Install
cypressif you haven't already:
npm install cypress --save-dev
- Create an integration file (e.g.,
intercept_example.js) in thecypress/integrationfolder:
describe('Intercept Example', () => {
it('Intercept and stub a request', () => {
cy.server(); // Enable interception
cy.route({
method: 'GET',
url: '/api/example-data', // Intercept requests to this URL
response: (xhr, res) => {
// Modify the response here if needed
const fakeData = [1, 2, 3];
res.send(fakeData);
},
});
cy.visit('http://your-test-app.com');
cy.contains('[data-cy=example-data]', '1').should('exist'); // Verify the modified response
cy.contains('[data-cy=example-data]', '2').should('exist');
cy.contains('[data-cy=example-data]', '3').should('exist');
});
});
In this example, we intercept requests to /api/example-data, stub a response with an array of numbers [1, 2, 3], and verify that the modified data appears on the test app.
Common Mistakes
- Not setting up the interception properly (e.g., forgetting to call
cy.server()in Cypress) - Modifying requests or responses without understanding their implications (e.g., changing request headers that affect authentication)
- Failing to verify that the intercepted data is being used correctly in your tests
- Not handling multiple intercepted requests appropriately (e.g., using
cy.route()with an object instead of a function for more control) - Misconfiguring proxies when using Selenium or Playwright
Practice Questions
- How can you modify the response body in Cypress intercepts?
- What is the difference between
cy.route()andcy.intercept()in Cypress? - How would you stub a GET request to an external API using Selenium with
webdriverio-proxy? - How can you verify that intercepted data is being used correctly in your tests?
- What are some potential pitfalls when using network interception in test automation?
FAQ
Q: Can I use intercepts for testing AJAX calls?
A: Yes, you can use intercepts to test AJAX calls made by your application.
Q: How do I handle multiple intercepted requests in Cypress?
A: You can use cy.route() with an object that includes a response property and a function for more control over each intercepted request.
Q: Can I use network interception for testing frontend-only applications (e.g., SPAs)?
A: Yes, you can use network interception for testing frontend-only applications as long as they make HTTP/HTTPS requests during their lifecycle.
Q: How do I troubleshoot issues with network interception in Selenium or Playwright?
A: You can use tools like MITMProxy or Charles Proxy to inspect and debug intercepted requests and responses.
Q: Can I use network interception for testing web sockets?
A: Web sockets are different from traditional HTTP/HTTPS requests, so they cannot be easily intercepted using the methods described in this lesson. However, there are specialized tools available to test web socket communication, such as WebSocket.js and ws.