Skip to main content

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.

For the Classic setup, see CDP in Testplane and the CDP interception guide. The comparison below describes @testplane/webdriverio 9.6.2; the runnable example uses BiDi.

Usage​

await browser.mock(url, filters)

Command parameters​

ParameterBiDiClassic/CDP
urlURLPattern string: an absolute HTTP(S) pattern or pathname such as /api/items.Glob string or RegExp.
methodHTTP method string or predicate.Same.
requestHeadersRequest-header object or predicate.Same.
responseHeadersResponse-header object or predicate.Not applied.
headersDo not use; use responseHeaders for responses.Filters response headers, not request headers.
postDataNot applied.Request body string or predicate.
statusCodeResponse status number or predicate.Same.

Pass the filters together in the optional second argument. In BiDi, statusCode and responseHeaders filter responses, not outgoing requests: request, redirect or abort can already have acted before the status is known. Use a method or request-header filter to narrow those rules. 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 matching network events, not just completed responses:

  • BiDi: network.responseStarted objects, for example call.request.url and call.response.status. This does not guarantee a fully downloaded body.
  • Classic/CDP: entries have url, body, headers, responseHeaders and statusCode. An aborted or locally fulfilled request can be recorded without an HTTP response from the server.

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.

EventBiDiClassic/CDP
requestnetwork.beforeRequestSent event: URL at event.request.url.CDP Fetch.requestPaused event.
matchNot emitted in this version, although declared in types.Matched response entry.
overwriteRequest or response event that received an override.Overridden response parameters.
failAborted request ID.Object with requestId and errorReason.
continueContinued 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();
}
});

References​

This page draws on the original WebdriverIO article.