emulate
Overview
Override part of the browser environment, such as the user agent or clock. Use the returned cleanup function or clock object to restore the environment in the same test.
Usage
browser.emulate(scope, options)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
scope | string | Required | One of clock, geolocation, userAgent, device, colorScheme, onLine. |
options | Depends on scope | Required except clock | Options for the selected scope, described below. |
Supported scopes:
clock— Fake-timer options, includingnowandtoFake; virtual timers advance throughtick.geolocation— Coordinates, for example{ latitude: 52.52, longitude: 13.405 }, returned bynavigator.geolocation.getCurrentPosition. This does not overridewatchPositionor grant browser permissions.userAgent— A string overridingnavigator.userAgent, not HTTP request headers.device— A supported device profile name; changes viewport, DPR and user agent, not engine or touch hardware.colorScheme—"light"or"dark"; affectsmatchMedia, not CSS media queries in this implementation.onLine— A boolean overridingnavigator.onLine; does not block network requests.
Result
For clock, Promise<ClockManager>; otherwise, a promise resolving to an asynchronous restore function. Clock methods include tick(milliseconds), setSystemTime(dateOrTimestamp), restore() and install(options).
Limitations
Requires WebDriver BiDi (webSocketUrl: true). Enable emulation before navigation: most overrides take effect when a new document loads. The clock also changes in the current document. Use just one cleanup method per emulation.
With @testplane/webdriverio 9.6.2, clock.restore() restores native timers in the current document but leaves a clock initialization script registered for later navigations. Use testsPerSession: 1 for clock tests if a later test must start with a clean session.
Example
Set baseUrl to your local HTTP test site, where / returns an HTML page. Run the example in a regular Testplane test file.
const assert = require("node:assert/strict");
it("emulate: control time without waiting", async ({ browser }) => {
await browser.url("/");
const clock = await browser.emulate("clock", {
now: new Date("2025-01-01T00:00:00.000Z"),
toFake: ["Date", "setTimeout", "clearTimeout"],
});
try {
await browser.execute(() => {
window.timerFired = false;
setTimeout(() => {
window.timerFired = true;
}, 1000);
});
assert.equal(await browser.execute(() => window.timerFired), false);
await clock.tick(1000);
assert.equal(await browser.execute(() => window.timerFired), true);
assert.equal(
await browser.execute(() => new Date().toISOString()),
"2025-01-01T00:00:01.000Z",
);
} finally {
await clock.restore();
}
});