Skip to main content

clear

Overview​

Clears mock.calls history but retains the interceptor, override rules and event listeners. The next matching response is added to history again. To remove rules without deleting a BiDi mock, use reset; to remove the interceptor, use restore.

Usage​

await mock.clear()

Parameters and result​

Takes no arguments. BiDi synchronously returns the same mock; Classic/CDP has no useful return value. The example uses await, which also works with asynchronous implementations. Clear history before waitForResponse when waiting for a new response rather than a previously recorded one.

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.clear: clear history but retain response rules", async ({ browser }) => {
await browser.url("/");
await browser.sessionSubscribe({
events: ["network.beforeRequestSent", "network.responseStarted"],
});
const mock = await browser.mock("/api/items");
try {
mock.respond({ source: "mocked" });
await browser.execute(async () =>
(await fetch("/api/items", { cache: "no-store" })).json(),
);
await mock.waitForResponse({ timeout: 3000 });
assert.equal(mock.calls.length, 1);
await mock.clear();
assert.equal(mock.calls.length, 0);
const body = await browser.execute(async () =>
(await fetch("/api/items", { cache: "no-store" })).json(),
);
assert.equal(body.source, "mocked");
await mock.waitForResponse({ timeout: 3000 });
assert.equal(mock.calls.length, 1);
} finally {
await mock.restore();
}
});

References​

This page draws on the original WebdriverIO article.