Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/basic-guides/selectors.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,10 @@ Use this approach if:
- you need access to elements inside the shadow root
- you are working with a design system based on Web Components

## Custom locator strategies {/* #custom-locator-strategies */}

If standard selectors are insufficient, register a strategy with [browser.addLocatorStrategy](../commands/browser/addLocatorStrategy.mdx). Use [browser.custom$](../commands/browser/customDollar.mdx) for one element and [browser.custom$$](../commands/browser/customDollarDollar.mdx) for multiple elements. To search within an element, use [element.custom$](../commands/element/customDollar.mdx) or [element.custom$$](../commands/element/customDollarDollar.mdx). The strategy runs in the browser, so pass data as arguments rather than through Node.js closures. The command pages contain verified examples.

## Testing Library

Testing Library allows you to find elements the way users do — by text, element type, or other attributes that don't depend on your layout details.
Expand Down
120 changes: 65 additions & 55 deletions docs/basic-guides/user-environment-emulation.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -327,60 +327,65 @@ it("applies styles for the dark color scheme", async ({ browser }) => {
});
```

## Network
## Network {/* #network */}

### Offline mode
### Offline mode {/* #offline-mode */}

To test how the application works without a network connection, use [`browser.throttleNetwork("offline")`][throttle-network].
Use [throttleNetwork][throttle-network] to block actual requests. The example requires Chromium with CDP/Puppeteer access, one tab, `isolation: false` and `testsPerSession: 1`: the implementation selects the first Puppeteer page. Navigate before disabling the network.

For example, you can test the error message displayed when a network request fails:
In the verified Testplane 9.3.2 / WDIO 9.6.2 / Chrome 150 combination, the `online` profile did not restore connectivity after `offline`. The example therefore ends the offline session and checks connectivity in a new one rather than promising recovery through that call. Point `baseUrl` to a test HTTP server that returns `200` at the root path.

```typescript
it("shows a message when there is no network connection", async ({ browser }) => {
await browser.url("/");
```javascript testplane=browser-throttle-network
const assert = require("node:assert/strict");

// Configure testsPerSession: 1 so this offline session is not reused.
it("throttleNetwork: check a failed request while offline", async ({ browser }) => {
await browser.url("/");
await browser.throttleNetwork("offline");
const failed = await browser.execute(async () => {
try {
await fetch("/?offline-check", { cache: "no-store" });
return false;
} catch {
return true;
}
});
assert.equal(failed, true);
});

const loadOrders = await browser.getByTestId("load-orders");
await loadOrders.click();

const networkError = await browser.findByTestId("network-error");
await expect(networkError).toHaveText("No network connection");

await browser.throttleNetwork("online");
it("throttleNetwork: the next session starts online", async ({ browser }) => {
await browser.url("/");
const status = await browser.execute(async () => {
const response = await fetch("/?online-check", { cache: "no-store" });
return response.status;
});
assert.equal(status, 200);
});
```

Load the page first, then disable the network before the action that sends a request. Unlike `emulate()`, `throttleNetwork()` must be called after navigation. To restore the normal network mode, use the `"online"` profile.
### Slow connection {/* #slow-connection */}

### Slow connection
Pass an object to [throttleNetwork][throttle-network] to limit throughput. The example uses the same isolation requirements. The server at `baseUrl` must serve HTML at `/` and JSON with `source: "original"` at `/api/items`.

To test the interface over a slow connection, pass network parameters to [`browser.throttleNetwork()`][throttle-network]:

```typescript
it("shows the loading state on a slow network", async ({ browser }) => {
await browser.url("/orders");
```javascript testplane=related-slow-network
const assert = require("node:assert/strict");

it("slow network: fetch data under custom throughput limits", async ({ browser }) => {
await browser.url("/");
await browser.throttleNetwork({
offline: false,
latency: 500,
downloadThroughput: (50 * 1024) / 8,
uploadThroughput: (20 * 1024) / 8,
});

const loadOrders = await browser.getByTestId("load-orders");
await loadOrders.click();

const loading = await browser.findByTestId("loading");
await expect(loading).toBeDisplayed();

await browser.throttleNetwork("online");
const data = await browser.execute(async () =>
(await fetch("/api/items", { cache: "no-store" })).json(),
);
assert.equal(data.source, "original");
});
```

The object contains four fields: `offline`, the `latency` in milliseconds, and the `downloadThroughput` and `uploadThroughput` rates in bytes per second.

For common network conditions, you do not have to specify the parameters manually. Pass the name of a predefined profile instead of an object, such as `"Good3G"` or `"offline"`.
`offline` enables offline mode, `latency` is in milliseconds, and `downloadThroughput` and `uploadThroughput` are in bytes per second. You can pass a preset such as `Good3G` instead of an object. The throttled session is not reused by the next test.

### navigator.onLine

Expand All @@ -400,25 +405,30 @@ The emulation persists until the end of the session, so restore it in the same t

`browser.emulate("onLine", false)` only changes the value of `navigator.onLine`; it does not disable the network, and HTTP requests continue to work.

## CPU performance
## CPU performance {/* #cpu-performance */}

To test the interface with limited CPU performance, use [`browser.throttleCPU()`][throttle-cpu].
[throttleCPU][throttle-cpu] slows down code execution in Chromium through CDP/Puppeteer. As with network throttling, use one tab and `isolation: false`: the command targets the first Puppeteer page. Navigate before calling it. Set `baseUrl` to a test HTML page.

For example, you can test a scenario with 4× CPU slowdown as follows:
The example applies a 2× slowdown and removes it in `finally`.

```typescript
it("works with a throttled CPU", async ({ browser }) => {
await browser.throttleCPU(4);
```javascript testplane=browser-throttle-cpu
const assert = require("node:assert/strict");

it("throttleCPU: run a page with a slower CPU", async ({ browser }) => {
await browser.url("/");

// ...

await browser.throttleCPU(1);
try {
await browser.throttleCPU(2);
await browser.execute(() => {
document.body.innerHTML = "<button>Ready</button>";
});
assert.equal(await browser.$("button").getText(), "Ready");
} finally {
await browser.throttleCPU(1);
}
});
```

The higher the slowdown factor, the slower the code runs. A value of `1` disables throttling.
A larger factor slows code execution further. A value of `1` disables throttling.

## Geolocation

Expand Down Expand Up @@ -551,26 +561,26 @@ describe("dark color scheme", () => {

If a setting must remain active for the entire session, create a separate browser configuration for it. This approach is more convenient for setting the browser language, running tests with JavaScript disabled, and setting a fixed window size with [`windowSize`][window-size].

[emulate]: https://webdriver.io/docs/api/browser/emulate
[emulate]: ../commands/browser/emulate.mdx
[webdriver-bidi]: https://w3c.github.io/webdriver-bidi/
[set-viewport]: https://webdriver.io/docs/api/browser/setViewport
[set-viewport]: ../commands/browser/setViewport.mdx
[set-window-size]: ../commands/browser/setWindowSize.mdx
[window-size]: ../reference/config/browsers.mdx#window_size
[how-to-use-cdp]: ../guides/how-to-use-cdp.mdx
[emulate-device]: https://webdriver.io/docs/emulation#device
[emulate-user-agent]: https://webdriver.io/docs/emulation#user-agent
[emulate-device]: ../commands/browser/emulate.mdx#parameters
[emulate-user-agent]: ../commands/browser/emulate.mdx#parameters
[get-puppeteer]: ../commands/browser/getPuppeteer.mdx
[page-set-user-agent]: https://pptr.dev/api/puppeteer.page.setuseragent
[cdp-set-locale-override]: https://chromedevtools.github.io/devtools-protocol/tot/Emulation/#method-setLocaleOverride
[page-emulate-timezone]: https://pptr.dev/api/puppeteer.page.emulatetimezone
[emulate-clock]: https://webdriver.io/docs/emulation#clock
[clock-tick]: https://webdriver.io/docs/api/clock/tick
[emulate-color-scheme]: https://webdriver.io/docs/emulation#color-scheme
[emulate-clock]: ../commands/browser/emulate.mdx#parameters
[clock-tick]: ../commands/browser/emulate.mdx#result
[emulate-color-scheme]: ../commands/browser/emulate.mdx#parameters
[cdp-set-emulated-media]: https://chromedevtools.github.io/devtools-protocol/tot/Emulation/#method-setEmulatedMedia
[throttle-network]: https://webdriver.io/docs/api/browser/throttleNetwork
[emulate-online]: https://webdriver.io/docs/emulation#online-property
[throttle-cpu]: https://webdriver.io/docs/api/browser/throttleCPU
[emulate-geolocation]: https://webdriver.io/docs/emulation#geolocation
[throttle-network]: ../commands/browser/throttleNetwork.mdx
[emulate-online]: ../commands/browser/emulate.mdx#parameters
[throttle-cpu]: ../commands/browser/throttleCPU.mdx
[emulate-geolocation]: ../commands/browser/emulate.mdx#parameters
[set-permissions]: https://webdriver.io/docs/api/webdriver#setpermissions
[restore]: https://webdriver.io/docs/api/browser/restore
[restore]: ../commands/browser/restore.mdx
[testing-library-guide]: ../guides/how-to-add-testing-library.mdx
58 changes: 58 additions & 0 deletions docs/commands/browser/addInitScript.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# addInitScript

## Overview {/* #overview */}

Run a function in new documents of the current tab or window before page scripts execute. Use this to prepare browser-side values before the application reads them. The function also runs in newly attached or navigated child frames within that top-level browsing context.

The script is registered for the tab or window that is current when `addInitScript` is called. It does not automatically apply to other tabs or windows, including those opened later. To use it there, switch to the target tab or window and register it separately before navigation.

## Usage {/* #usage */}

`browser.addInitScript(script, ...args)`

## Parameters {/* #parameters */}

| **Parameter** | **Type** | **Default** | **Description** |
| ------------- | ----------- | ----------- | ------------------------------------------------------------------------ |
| `script` | `Function` | Required | A function executed in the browser, without access to Node.js variables. |
| `args` | `unknown[]` | [] | Arguments serialized as JSON and passed to the function. |

## Result {/* #result */}

`Promise<InitScript>`. Call `script.on("data", listener)` before navigation to receive values sent by the script's final `emit` argument. Subscribing with `on` is synchronous; `script.remove()` returns a promise.

## Limitations {/* #limitations */}

Requires WebDriver BiDi (`webSocketUrl: true`). Register the function before navigation. `await script.remove()` prevents injection into future documents; it does not undo changes in the current one.

In `@testplane/webdriverio` 9.6.2, pass a function, not a string. Use ordinary quotes in its source: template literals can break the injected script. Characters outside Latin-1 (such as Cyrillic) in the function source or serialized arguments can prevent registration.

## Example {/* #examples */}

On the [example site](../overview.mdx#run-examples), `/navigation` runs `window.initialSeed = window.navigationSeed ?? null` as it loads. The test checks what the **page script** saw, both with and without the init script.

```javascript testplane=browser-add-init-script
const assert = require("node:assert/strict");

it("addInitScript: set a value before page scripts", async ({ browser }) => {
const script = await browser.addInitScript(value => {
window.navigationSeed = value;
}, 42);

try {
await browser.url("/navigation");
assert.equal(await browser.execute(() => window.initialSeed), 42);
} finally {
await script.remove();
}

await browser.url("/navigation");
assert.equal(await browser.execute(() => window.initialSeed), null);
});
```

## See also {/* #see-also */}

- [execute](./execute.mdx)
- [url](./url.mdx)
- [emulate](./emulate.mdx)
48 changes: 48 additions & 0 deletions docs/commands/browser/addLocatorStrategy.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# addLocatorStrategy

## Overview {/* #overview */}

Register a reusable way to find elements. After registration, call the strategy through `custom$` or `custom$$` on the browser or an element.

## Usage {/* #usage */}

`browser.addLocatorStrategy(name, strategy)`

## Parameters {/* #parameters */}

| **Parameter** | **Type** | **Default** | **Description** |
| ------------- | ---------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | `string` | Required | A unique strategy name within the browser instance. |
| `strategy` | `Function` | Required | A browser-side function that returns a DOM element or an array of DOM elements. Convert a NodeList with Array.from before returning it. |

## Result {/* #result */}

`void`. Registration is synchronous; it does not find elements by itself.

## Limitations {/* #limitations */}

Register the strategy before its first use. Registering an existing name throws an error. The callback runs in the browser and cannot read Node.js closures. For reusable test setup, register it in `prepareBrowser`.

## Example {/* #examples */}

Set `baseUrl` to your local HTTP test site, where `/` returns an HTML page. Run the example in a regular Testplane test file.

```javascript testplane=browser-add-locator-strategy
const assert = require("node:assert/strict");

it("addLocatorStrategy: find by data attribute", async ({ browser }) => {
await browser.url("/");
await browser.execute(() => {
document.body.innerHTML = '<button data-test="save">Save</button>';
});
browser.addLocatorStrategy("byTest", value => document.querySelector(`[data-test="${value}"]`));
const button = await browser.custom$("byTest", "save");
assert.equal(await button.getText(), "Save");
});
```

## See also {/* #see-also */}

- [custom$](./customDollar.mdx)
- [custom$$](./customDollarDollar.mdx)
- [prepareBrowser](../../reference/config/prepare-browser.mdx)
48 changes: 48 additions & 0 deletions docs/commands/browser/customDollar.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# custom$

## Overview {/* #overview */}

Find one element using a strategy registered with `addLocatorStrategy`. The strategy controls how the element is selected.

## Usage {/* #usage */}

`browser.custom$(strategyName, ...strategyArguments)`

## Parameters {/* #parameters */}

| **Parameter** | **Type** | **Default** | **Description** |
| ------------------- | ----------- | ----------- | ---------------------------------------------- |
| `strategyName` | `string` | Required | The name of a registered strategy. |
| `strategyArguments` | `unknown[]` | [] | Arguments passed to the browser-side strategy. |

## Result {/* #result */}

An awaitable element reference resolving to `WebdriverIO.Element`. If the strategy returns several elements, the first is used.

## Limitations {/* #limitations */}

An unknown strategy name throws an error. Finding an element does not imply that it is visible or clickable: use the corresponding waits or assertions. If the strategy finds nothing, subsequent element commands can fail.

## Example {/* #examples */}

Set `baseUrl` to your local HTTP test site, where `/` returns an HTML page. Run the example in a regular Testplane test file.

```javascript testplane=browser-custom-dollar
const assert = require("node:assert/strict");

it("custom$: find one element with a custom strategy", async ({ browser }) => {
await browser.url("/");
await browser.execute(() => {
document.body.innerHTML = '<button data-test="save">Save</button>';
});
browser.addLocatorStrategy("byTest", value => document.querySelector(`[data-test="${value}"]`));
const button = await browser.custom$("byTest", "save");
assert.equal(await button.getText(), "Save");
});
```

## See also {/* #see-also */}

- [addLocatorStrategy](./addLocatorStrategy.mdx)
- [custom$$](./customDollarDollar.mdx)
- [$](./$.mdx)
51 changes: 51 additions & 0 deletions docs/commands/browser/customDollarDollar.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# custom$$

## Overview {/* #overview */}

Find multiple elements with a registered custom strategy. Use `Array.from` in the strategy when a DOM API returns a NodeList.

## Usage {/* #usage */}

`browser.custom$$(strategyName, ...strategyArguments)`

## Parameters {/* #parameters */}

| **Parameter** | **Type** | **Default** | **Description** |
| ------------------- | ----------- | ----------- | ---------------------------------------------- |
| `strategyName` | `string` | Required | The name of a registered strategy. |
| `strategyArguments` | `unknown[]` | [] | Arguments passed to the browser-side strategy. |

## Result {/* #result */}

An awaitable collection resolving to an array of `WebdriverIO.Element` objects. No matches produces an empty array.

## Limitations {/* #limitations */}

An unknown strategy name throws an error. The command returns the matches found at the time of the query; it does not wait for a required number of elements.

## Example {/* #examples */}

Set `baseUrl` to your local HTTP test site, where `/` returns an HTML page. Run the example in a regular Testplane test file.

```javascript testplane=browser-custom-dollar-dollar
const assert = require("node:assert/strict");

it("custom$$: find several elements", async ({ browser }) => {
await browser.url("/");
await browser.execute(() => {
document.body.innerHTML = "<ul><li>First</li><li>Second</li></ul>";
});
browser.addLocatorStrategy("byCss", selector =>
Array.from(document.querySelectorAll(selector)),
);
const items = await browser.custom$$("byCss", "li");
assert.equal(items.length, 2);
assert.equal(await items[1].getText(), "Second");
});
```

## See also {/* #see-also */}

- [addLocatorStrategy](./addLocatorStrategy.mdx)
- [custom$](./customDollar.mdx)
- [$$](./$$.mdx)
Loading
Loading