Skip to main content

respondOnce

Overview​

Overrides one response. Repeated calls queue responses in call order. Once the one-shot queue is exhausted, subsequent requests receive original server responses.

Usage​

mock.respondOnce(overwrites, params)

Command parameters​

Parameters and BiDi versus Classic/CDP differences match respond, including headers, not header. BiDi accepts a string or JSON body; body callbacks and fetchResponse: false are not supported. The request reaches the server.

In BiDi, a one-shot rule removes the persistent rule and appends to other one-shot rules. In Classic/CDP, an earlier persistent rule can mask the queue. Do not assume identical behavior when mixing respond and respondOnce across protocols.

BiDi synchronously returns the same mock; Classic/CDP has no useful return value.

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("mock.respondOnce: consume BiDi responses in order", async ({ browser }) => {
await browser.url("/");
await browser.sessionSubscribe({
events: ["network.beforeRequestSent", "network.responseStarted"],
});
const mock = await browser.mock("/api/items");
try {
mock.respondOnce({ source: "first" });
mock.respondOnce({ source: "second" });
const sources = [];
for (let i = 0; i < 3; i++) {
const body = await browser.execute(async () =>
(await fetch("/api/items", { cache: "no-store" })).json(),
);
sources.push(body.source);
}
assert.deepEqual(sources, ["first", "second", "original"]);
} finally {
await mock.restore();
}
});

References​

This page draws on the original WebdriverIO article.