Implementation:Getgauge Taiko Intercept Handler
Overview
Intercept Handler is the custom handler function behavior of Taiko's intercept() function, which provides full programmatic control over how matching HTTP requests are processed.
Description
When intercept() is called with a URL pattern and a function as the second parameter, it registers a handler-based interceptor. For each matching request, the handler function is invoked with a context object containing the original request details and two helper functions: continue() to forward the request (with optional modifications) and respond() to return a mock response.
This is the most powerful form of interception, enabling dynamic, conditional, and stateful request handling that cannot be expressed with the simpler block, redirect, or mock patterns.
Usage
Handler functions are used for advanced interception scenarios such as conditional mocking (different behavior based on HTTP method), request modification (adding or changing headers), dynamic response generation, and request logging with pass-through.
Code Reference
Source Location
- Function action handling:
lib/handlers/fetchHandler.js:L93-99(function branch inhandleInterceptor, withcontinue/respondinjection)
The relevant code path in handleInterceptor:
// Function action branch in handleInterceptor
if (typeof action === 'function') {
action({
request: event.request,
continue: (override) => {
fetch.continueRequest({
requestId: event.requestId,
...override
});
},
respond: (mock) => {
mockResponse(event.requestId, mock);
}
});
return;
}
Signature
intercept(requestUrl, handler)
Import
const { intercept } = require('taiko');
I/O Contract
Inputs
| Parameter | Type | Required | Description |
|---|---|---|---|
requestUrl |
string or RegExp |
Yes | URL pattern to match against outgoing requests. |
handler |
Function |
Yes | Callback function invoked for each matching request. |
Handler function receives a context object with:
| Property | Type | Description |
|---|---|---|
request |
Object |
Original request details from CDP, including url, method, headers, and postData.
|
continue |
Function |
Forwards the request to the network. Accepts an optional override object. |
respond |
Function |
Returns a mock response. Accepts a mock response object (same format as object-based mocking). |
continue() override object properties (all optional):
| Property | Type | Description |
|---|---|---|
url |
string |
Override the request URL. |
method |
string |
Override the HTTP method (GET, POST, etc.). |
postData |
string |
Override the request body. |
headers |
Array |
Override request headers. |
Outputs
| Return Type | Description |
|---|---|
Promise<void> |
Resolves when the handler interceptor has been registered. |
Side Effect: For each matching request, the handler function is invoked. The handler must call either continue() or respond() to resolve the intercepted request. Failing to call either will leave the request permanently paused.
Usage Examples
Conditional mocking based on HTTP method:
const { openBrowser, goto, intercept, closeBrowser } = require('taiko');
(async () => {
await openBrowser();
await intercept('https://api.example.com/data', (req) => {
if (req.request.method === 'POST') {
req.respond({
status: 201,
contentType: 'application/json',
body: { id: 42, created: true }
});
} else {
req.continue();
}
});
await goto('https://example.com');
await closeBrowser();
})();
Modify request headers before forwarding:
await intercept('https://api.example.com', (req) => {
req.continue({
headers: [
...Object.entries(req.request.headers).map(
([name, value]) => ({ name, value })
),
{ name: 'Authorization', value: 'Bearer test-token-123' }
]
});
});
Dynamic response based on request content:
await intercept('https://api.example.com/search', (req) => {
const url = new URL(req.request.url);
const query = url.searchParams.get('q');
if (query === 'empty') {
req.respond({
status: 200,
contentType: 'application/json',
body: { results: [] }
});
} else {
req.respond({
status: 200,
contentType: 'application/json',
body: { results: [{ id: 1, title: `Result for ${query}` }] }
});
}
});
Request logging with pass-through:
const capturedRequests = [];
await intercept('https://api.example.com', (req) => {
// Log the request details for later assertion
capturedRequests.push({
url: req.request.url,
method: req.request.method,
body: req.request.postData
});
// Allow the request to proceed normally
req.continue();
});
await goto('https://example.com');
// Later: assert on capturedRequests
Redirect POST to different URL while modifying body:
await intercept('https://api.example.com/submit', (req) => {
req.continue({
url: 'https://api.staging.com/submit',
postData: JSON.stringify({
...JSON.parse(req.request.postData),
testMode: true
})
});
});