mock
Overview
Creates a network interceptor. The returned object can observe requests, replace responses or abort loading. Capabilities depend on the session protocol.
- WebDriver BiDi: interception through BiDi network events, including request overrides, redirects and rule reset.
- Classic with CDP/Puppeteer: the legacy implementation for a compatible browser, not a universal Classic WebDriver capability.
- Sauce Labs WebDriver interception: a provider extension with a different API and no events; do not assume the BiDi example works with it.
See CDP setup and request interception. The differences below describe Testplane 9.3.2 / WDIO 9.6.2.
Usage
await browser.mock(url, filters)
Command parameters
| Parameter | BiDi | Classic/CDP |
|---|---|---|
url | URLPattern string: an absolute HTTP(S) pattern or pathname such as /api/items. | Glob string or RegExp. |
method | HTTP method string or predicate. | Same. |
requestHeaders | Request-header object or predicate. | Same. |
responseHeaders | Response-header object or predicate. | Not applied. |
headers | Do not use; use responseHeaders for responses. | Filters response headers, not request headers. |
postData | Not applied. | Request body string or predicate. |
statusCode | Response status number or predicate. | Same. |
Filters are optional. Response filters are evaluated at the response stage: the BiDi request event can occur earlier. CDP globs and BiDi URLPattern strings are not interchangeable.
Result
Returns a Promise with a mock object. Shared operations: respond, respondOnce, abort, abortOnce, waitForResponse, clear and restore. Signatures can differ between implementations.
BiDi only: request, requestOnce, redirect, redirectOnce and reset.
mock.calls stores response history:
- BiDi:
network.responseStartedobjects, for examplecall.request.urlandcall.response.status. This does not guarantee a fully downloaded body. - Classic/CDP: entries with
url,body,headers,responseHeaders,statusCode.
Do not treat one implementation's fields as a shared contract. clear() clears history but retains rules. restore() removes the interceptor; await it in finally.
Events
Subscribe with mock.on(name, listener). Listeners run in Node.js, not in the browser.
| Event | BiDi | Classic/CDP |
|---|---|---|
request | network.beforeRequestSent event: URL at event.request.url. | CDP Fetch.requestPaused event. |
match | Not emitted in this version, although declared in types. | Matched response entry. |
overwrite | Request or response event that received an override. | Overridden response parameters. |
fail | Aborted request ID. | Object with requestId and errorReason. |
continue | Continued request ID. | Continued request ID. |
An event alone is not proof that the entire network exchange has finished.
Example
The example uses Chrome with WebDriver BiDi. Point baseUrl to a test HTTP server: / serves an HTML page, and /api/items returns JSON with source: "original" and status 200. The explicit event subscription supports new sessions in the same worker in WDIO 9.6.2.
const assert = require("node:assert/strict");
it("browser.mock: observe and replace a BiDi response", async ({ browser }) => {
await browser.url("/");
await browser.sessionSubscribe({
events: ["network.beforeRequestSent", "network.responseStarted"],
});
const mock = await browser.mock("/api/items", { method: "GET", statusCode: 200 });
const seenUrls = [];
mock.on("request", event => seenUrls.push(event.request.url));
try {
mock.respond({ source: "mocked" });
const body = await browser.execute(async () =>
(await fetch("/api/items", { cache: "no-store" })).json(),
);
await mock.waitForResponse({ timeout: 3000 });
assert.equal(body.source, "mocked");
assert.equal(mock.calls.length, 1);
assert.ok(mock.calls[0].request.url.endsWith("/api/items"));
assert.ok(seenUrls.some(url => url.endsWith("/api/items")));
} finally {
await mock.restore();
}
});
Related commands
References
This page draws on the original WebdriverIO article.