Implementation:Getgauge Taiko Intercept Mock
Overview
Intercept Mock is the response mocking behavior of Taiko's intercept() function, which returns fabricated HTTP responses for matching requests without making actual network calls.
Description
When intercept() is called with a URL pattern and an object as the second parameter, it registers a mock response interceptor. Any matching request is fulfilled using the CDP Fetch.fulfillRequest method with a constructed response containing the specified status code, headers, and body content. No network activity occurs — the response is fabricated entirely within the browser.
The mock response object is processed by the internal mockResponse function, which handles body serialization, base64 encoding, content-type detection, and header construction.
Usage
Response mocking is used when tests need to control exactly what data the application receives from network requests. This enables testing of specific UI states, error handling, and data-dependent behavior without requiring a running backend.
Code Reference
Source Location
- Object action handling:
lib/handlers/fetchHandler.js:L113-116(object branch inhandleInterceptor) - Mock response construction:
lib/handlers/fetchHandler.js:L123-146(mockResponsefunction)
The relevant code paths:
// Object action branch in handleInterceptor
if (typeof action === 'object') {
mockResponse(event.requestId, action);
return;
}
// mockResponse function
function mockResponse(requestId, response) {
let body = response.body;
if (typeof body === 'object') {
body = JSON.stringify(body);
}
const encodedBody = Buffer.from(body || '').toString('base64');
const responseHeaders = [
{ name: 'content-type', value: response.contentType || 'text/plain' },
{ name: 'content-length', value: String(Buffer.byteLength(body || '')) },
...(response.headers ? Object.entries(response.headers).map(
([name, value]) => ({ name, value })
) : [])
];
fetch.fulfillRequest({
requestId,
responseCode: response.status || 200,
responseHeaders,
body: encodedBody
});
}
Signature
intercept(requestUrl, responseData)
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. |
responseData |
Object |
Yes | Mock response configuration object. |
responseData object properties:
| Property | Type | Default | Description |
|---|---|---|---|
status |
number |
200 |
HTTP status code for the mock response. |
headers |
Object |
{} |
Custom response headers as key-value pairs. |
contentType |
string |
"text/plain" |
MIME type of the response body. Sets the content-type header.
|
body |
string or Object |
"" |
Response body. Objects are automatically serialized to JSON via JSON.stringify().
|
Outputs
| Return Type | Description |
|---|---|
Promise<void> |
Resolves when the mock interceptor has been registered. |
Side Effect: Matching requests receive a fabricated response via Fetch.fulfillRequest. The body is base64-encoded, content-type and content-length headers are automatically set, and custom headers are merged.
Usage Examples
Mock a JSON API response:
const { openBrowser, goto, intercept, closeBrowser } = require('taiko');
(async () => {
await openBrowser();
await intercept('https://api.example.com/users', {
status: 200,
contentType: 'application/json',
body: {
users: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]
}
});
await goto('https://example.com');
await closeBrowser();
})();
Mock an error response:
await intercept('https://api.example.com/data', {
status: 500,
contentType: 'application/json',
body: { error: 'Internal Server Error', message: 'Database connection failed' }
});
await goto('https://example.com');
// Assert error state UI is displayed
Mock an empty list response:
await intercept('https://api.example.com/items', {
status: 200,
contentType: 'application/json',
body: { items: [], total: 0 }
});
await goto('https://example.com');
// Assert empty state UI is displayed
Mock with custom headers:
await intercept('https://api.example.com/secure', {
status: 200,
contentType: 'application/json',
headers: {
'x-request-id': 'test-123',
'cache-control': 'no-store'
},
body: { authorized: true }
});
Mock a 404 Not Found:
await intercept('https://api.example.com/missing', {
status: 404,
contentType: 'application/json',
body: { error: 'Not Found' }
});
await goto('https://example.com/page-that-fetches-missing');
// Assert 404 handling in UI