diff --git a/docs/basic-guides/selectors.mdx b/docs/basic-guides/selectors.mdx index c4828a5b..e6a9f1f4 100644 --- a/docs/basic-guides/selectors.mdx +++ b/docs/basic-guides/selectors.mdx @@ -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. diff --git a/docs/basic-guides/user-environment-emulation.mdx b/docs/basic-guides/user-environment-emulation.mdx index d401a8df..2c2f2bfc 100644 --- a/docs/basic-guides/user-environment-emulation.mdx +++ b/docs/basic-guides/user-environment-emulation.mdx @@ -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 @@ -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 = ""; + }); + 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 @@ -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 diff --git a/docs/commands/browser/addInitScript.mdx b/docs/commands/browser/addInitScript.mdx new file mode 100644 index 00000000..0f4efd96 --- /dev/null +++ b/docs/commands/browser/addInitScript.mdx @@ -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`. 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) diff --git a/docs/commands/browser/addLocatorStrategy.mdx b/docs/commands/browser/addLocatorStrategy.mdx new file mode 100644 index 00000000..000460d6 --- /dev/null +++ b/docs/commands/browser/addLocatorStrategy.mdx @@ -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 = ''; + }); + 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) diff --git a/docs/commands/browser/customDollar.mdx b/docs/commands/browser/customDollar.mdx new file mode 100644 index 00000000..0e961ece --- /dev/null +++ b/docs/commands/browser/customDollar.mdx @@ -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 = ''; + }); + 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) diff --git a/docs/commands/browser/customDollarDollar.mdx b/docs/commands/browser/customDollarDollar.mdx new file mode 100644 index 00000000..7c7c16ab --- /dev/null +++ b/docs/commands/browser/customDollarDollar.mdx @@ -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 = ""; + }); + 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) diff --git a/docs/commands/browser/downloadFile.mdx b/docs/commands/browser/downloadFile.mdx new file mode 100644 index 00000000..e88f8abe --- /dev/null +++ b/docs/commands/browser/downloadFile.mdx @@ -0,0 +1,70 @@ +# downloadFile + +## Overview {/* #overview */} + +Copy a file downloaded by the browser on a Selenium Grid node to the Testplane process filesystem. This command does not download an arbitrary URL. + +## Requirements {/* #requirements */} + +Requires Selenium Grid with managed downloads enabled (`--enable-managed-downloads true`) and the capability `se:downloadsEnabled: true`. Chrome, Edge and Firefox are supported. Using `gridUrl: "local"` alone does not provide the Selenium downloads API. See the [Selenium documentation](https://www.selenium.dev/documentation/webdriver/drivers/remote_webdriver/#enable-downloads-in-the-grid). + +## Usage {/* #usage */} + +`browser.downloadFile(fileName, targetDirectory)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Description** | +| ----------------- | -------- | ----------------------------------------------------------- | +| `fileName` | `string` | A file name from `getDownloadableFiles().names`, not a URL. | +| `targetDirectory` | `string` | Local destination directory; created automatically. | + +## Result {/* #result */} + +`Promise<{ files: string[] }>`: absolute paths of extracted files. The command also leaves a `.zip` archive in the destination directory. In this version extraction errors are logged and can leave `files` empty; verify the result exists and has the expected contents. + +## Example {/* #examples */} + +Set `gridUrl` to your Grid address and enable `se:downloadsEnabled: true` in `desiredCapabilities`. Set `baseUrl` to a test HTTP site: `/` serves HTML, and `/report.csv` serves `name,value\nexample,42\n` with the header `Content-Disposition: attachment; filename="report.csv"`. + +Use a fresh browser session for this example (`testsPerSession: 1`), with `baseUrl` reachable **from the Grid node**. `getDownloadableFiles()` lists files already present; it does not wait for this download. `deleteDownloadableFiles()` deletes **all** managed downloads in the current session, not only `report.csv`. + +```javascript testplane=selenium-download-file suite=selenium +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const os = require("node:os"); +const path = require("node:path"); + +it("downloadFile: copy a browser download from Selenium Grid", async ({ browser }) => { + const targetDirectory = await fs.mkdtemp(path.join(os.tmpdir(), "testplane-download-")); + try { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = 'Download report'; + }); + await browser.$("a").click(); + await browser.waitUntil( + async () => { + const { names } = await browser.getDownloadableFiles(); + return names.includes("report.csv"); + }, + { timeout: 10000, timeoutMsg: "The CSV was not downloaded on the Grid node" }, + ); + const { files } = await browser.downloadFile("report.csv", targetDirectory); + const localFile = path.join(targetDirectory, "report.csv"); + assert.ok(files.includes(localFile)); + assert.equal(await fs.readFile(localFile, "utf8"), "name,value\nexample,42\n"); + } finally { + try { + await browser.deleteDownloadableFiles(); + } finally { + await fs.rm(targetDirectory, { recursive: true, force: true }); + } + } +}); +``` + +## See also {/* #see-also */} + +- [url](./url.mdx) +- [waitUntil](./waitUntil.mdx) diff --git a/docs/commands/browser/emulate.mdx b/docs/commands/browser/emulate.mdx new file mode 100644 index 00000000..7462c2e2 --- /dev/null +++ b/docs/commands/browser/emulate.mdx @@ -0,0 +1,74 @@ +# emulate + +## Overview {/* #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 {/* #usage */} + +`browser.emulate(scope, options)` + +## Parameters {/* #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, including `now` and `toFake`; virtual timers advance through `tick`. +- `geolocation` — Coordinates, for example `{ latitude: 52.52, longitude: 13.405 }`, returned by `navigator.geolocation.getCurrentPosition`. This does not override `watchPosition` or grant browser permissions. +- `userAgent` — A string overriding `navigator.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"`; affects `matchMedia`, not CSS media queries in this implementation. +- `onLine` — A boolean overriding `navigator.onLine`; does not block network requests. + +## Result {/* #result */} + +For `clock`, `Promise`; otherwise, a promise resolving to an asynchronous restore function. Clock methods include `tick(milliseconds)`, `setSystemTime(dateOrTimestamp)`, `restore()` and `install(options)`. + +## Limitations {/* #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](./restore.mdx#limitations) 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 {/* #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-emulate +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(); + } +}); +``` + +## See also {/* #see-also */} + +- [restore](./restore.mdx) +- [setViewport](./setViewport.mdx) +- [Environment emulation](../../basic-guides/user-environment-emulation.mdx) diff --git a/docs/commands/browser/executeAsync.mdx b/docs/commands/browser/executeAsync.mdx index c8572404..1d38b094 100644 --- a/docs/commands/browser/executeAsync.mdx +++ b/docs/commands/browser/executeAsync.mdx @@ -2,62 +2,47 @@ ## Overview {/* #overview */} -Use the `executeAsync` command to _asynchronously_ execute the specified JavaScript code in the context of the currently selected frame. +Runs JavaScript in the current frame and returns the value passed to a callback. This command is deprecated: prefer [execute](./execute.mdx) with an async function for new code. -The last argument of the command must be a callback that will be called as soon as the script completes its execution. The command passes the script result to the callback as an input parameter. - -The `script` argument defines the script to be executed as the body of a function. The function will be invoked with the provided array of `args`, and access to the values can be obtained through the `arguments` object in the specified order. The last argument must always be a callback function, which will be called once the script has been executed. - -Arguments can be any JSON primitives, arrays, or JSON objects. JSON objects that define a reference to a _WebElement_ will be converted to the corresponding DOM element. Similarly, any _WebElements_ in the script result will be returned to the client as _WebElement JSON_ objects. +The command injects the callback as the last argument of the **browser function**. Do not pass it as a separate argument to `browser.executeAsync`. Call the callback to complete the command. ## Usage {/* #usage */} -```javascript -await browser.executeAsync(script, arguments); -``` +`await browser.executeAsync(script, ...args)` -## Command Parameters {/* #parameters */} +## Command parameters {/* #parameters */} - - - - - - - +- `script`: a function or a string containing a function body. Runs in the browser without Node.js APIs or local closures. +- `args`: serializable arguments passed before the callback; WebElement references become DOM elements. - -
**Name****Type****Description**
scriptString or FunctionThe script to be executed.
argumentsAnyArguments for the script. The last argument must be a callback function, which will be called once the script has been executed.
+Returns a Promise with the value passed to the callback. In Classic, configure the `script` timeout using [setTimeout](./setTimeout.mdx). The BiDi implementation has no separate callback timer; always call it and bound the test with `testTimeout`. -## Usage Examples {/* #examples */} +## Example {/* #examples */} -```javascript -it("should execute async JavaScript on the page", async ({ browser }) => { - await browser.setTimeout({ script: 5000 }); +Set `baseUrl` to a test HTML page. +```javascript testplane=related-execute-async +const assert = require("node:assert/strict"); + +it("browser.executeAsync: return a result through the injected callback", async ({ browser }) => { + await browser.url("/"); const result = await browser.executeAsync( - function (a, b, c, d, done) { - // here we are in the browser context: no access to console or client - setTimeout(() => { - done(a + b + c + d); - }, 3000); + (a, b, done) => { + setTimeout(() => done(a + b), 20); }, - 1, - 2, - 3, 4, + 6, ); - - // here we are in the node.js context: access to console and client is available - console.log(result); // outputs: 10 + assert.equal(result, 10); }); ``` -## Related Commands {/* #related */} +## Related commands {/* #related */} -- [execute](../execute) -- [setTimeout](../setTimeout) +- [execute](./execute.mdx) +- [element.executeAsync](../element/executeAsync.mdx) +- [setTimeout](./setTimeout.mdx) -## References +## References {/* #references */} -We'd like to give credit to the original WebdriverIO docs [article](https://webdriver.io/docs/api/browser/executeAsync), from which we drew some information while writing our version. +This page draws on the [original WebdriverIO article](https://webdriver.io/docs/api/browser/executeAsync). diff --git a/docs/commands/browser/extendOptions.mdx b/docs/commands/browser/extendOptions.mdx new file mode 100644 index 00000000..8363a5a0 --- /dev/null +++ b/docs/commands/browser/extendOptions.mdx @@ -0,0 +1,62 @@ +# extendOptions + +## Overview {/* #overview */} + +Shallowly update the current WebdriverIO browser options. Use this for runtime client settings, such as wait timings, not to reconfigure the Testplane runner or renegotiate browser capabilities. + +## Usage {/* #usage */} + +`browser.extendOptions(options)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------- | ------------------------- | ----------- | ------------------------------------------------ | +| `options` | `Record` | Required | Top-level fields to assign to `browser.options`. | + +## Result {/* #result */} + +`Promise`: the command completes without a return value. + +## Limitations {/* #limitations */} + +Nested objects are replaced, not deeply merged. Existing fields not present in the argument are retained. The method does not validate option names or rebuild the session: changing a value only matters where a command reads that runtime option. It does not change the configuration returned by `getConfig()`. Save and restore modified values in `finally`. + +## Example {/* #examples */} + +Set `baseUrl` to a local HTTP test site where `/` serves an HTML page. Run the example in a Testplane test file. + +```javascript testplane=testplane-browser-extend-options +const assert = require("node:assert/strict"); + +it("extendOptions: change WebdriverIO wait settings for this browser", async ({ browser }) => { + const original = { + waitforTimeout: browser.options.waitforTimeout, + waitforInterval: browser.options.waitforInterval, + }; + const configuredTimeout = (await browser.getConfig()).waitTimeout; + assert.equal(typeof configuredTimeout, "number"); + try { + const result = await browser.extendOptions({ waitforTimeout: 1000, waitforInterval: 50 }); + assert.equal(result, undefined); + assert.equal(browser.options.waitforTimeout, 1000); + assert.equal(browser.options.waitforInterval, 50); + assert.equal((await browser.getConfig()).waitTimeout, configuredTimeout); + await browser.url("/"); + await browser.execute(() => { + setTimeout(() => { + document.body.innerHTML = '

Ready

'; + }, 100); + }); + await browser.$("#ready").waitForExist(); + assert.equal(await browser.$("#ready").getText(), "Ready"); + } finally { + await browser.extendOptions(original); + } +}); +``` + +## See also {/* #see-also */} + +- [getConfig](./getConfig.mdx) +- [waitUntil](./waitUntil.mdx) diff --git a/docs/commands/browser/getState.mdx b/docs/commands/browser/getState.mdx index e0c94576..44be4885 100644 --- a/docs/commands/browser/getState.mdx +++ b/docs/commands/browser/getState.mdx @@ -6,53 +6,55 @@ import Version from "../../_partials/specs/version.mdx"; ## Overview {/* #overview */} -A browser command that restores the session state from a file which previously saved using the [saveState][saveState] command. +Reads a JSON state file created by [saveState](./saveState.mdx) and returns its contents. It **does not restore browser state**: cookies, storage and the current page stay unchanged. To restore the session, use [restoreState](./restoreState.mdx). ## Usage {/* #usage */} -```typescript -import type { SaveStateData } from "testplane"; +`await browser.getState(options)` -const stateDump: SaveStateData = await browser.getState({ - path: "./stateDump.json", -}); -``` +## Command parameters {/* #parameters */} + +| Parameter | Type | Description | +| -------------- | -------- | ------------------------------------------------------------------------------------------- | +| `options.path` | `string` | Path to the JSON file. Relative paths resolve from the Testplane process working directory. | + +When `options` is omitted, the command uses `browser.config.stateOpts`. An explicit object is not merged with configuration: `getState({})` does not inherit the configured path. + +## Result and errors {/* #result */} + +Returns a Promise with the parsed data. A `saveState` file contains `SaveStateData`: an optional `cookies` array and `framesData`, with `localStorage` and `sessionStorage` grouped by origin. The command does not validate the JSON schema. -## Command Parameters {/* #parameters */} - - - - - - - - - - - - - - - - - - -
**Name****Type****Default****Description**
path`string``-`Path to file with state.
- -## Usage Examples {/* #examples */} - -Save state in file. - -```typescript -it("test", async ({ browser }) => { - const stateData = await browser.getState({ - path: "./stateDump.json", - }); +If no path is set, the command logs an error and returns `null`. File read and JSON parsing errors reject the promise. A state file can contain session cookies and storage values: keep it out of source control and test logs. + +## Example {/* #examples */} + +Set `baseUrl` to a test HTML page. The example saves localStorage to a temporary file, changes the browser value and verifies that reading the file does not restore the session. + +```javascript testplane=related-get-state +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const os = require("node:os"); +const path = require("node:path"); + +it("getState: read a saved file without restoring the session", async ({ browser }) => { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), "testplane-state-")); + const statePath = path.join(directory, "state.json"); + try { + await browser.url("/"); + const origin = new URL(await browser.getUrl()).origin; + await browser.execute(() => localStorage.setItem("example", "saved")); + await browser.saveState({ path: statePath, cookies: false, localStorage: true }); + await browser.execute(() => localStorage.setItem("example", "current")); + const state = await browser.getState({ path: statePath }); + assert.equal(state.framesData[origin].localStorage.example, "saved"); + assert.equal(await browser.execute(() => localStorage.getItem("example")), "current"); + } finally { + await fs.rm(directory, { recursive: true, force: true }); + } }); ``` -## Related Commands {/* #related */} - -- [saveState][saveState] +## Related commands {/* #related */} -[saveState]: ../saveState +- [saveState](./saveState.mdx) +- [restoreState](./restoreState.mdx) diff --git a/docs/commands/browser/mock.mdx b/docs/commands/browser/mock.mdx index 08955c52..eb1f7289 100644 --- a/docs/commands/browser/mock.mdx +++ b/docs/commands/browser/mock.mdx @@ -1,139 +1,97 @@ -import Admonition from "@theme/Admonition"; - # mock ## Overview {/* #overview */} -Use the `mock` command to mock the response to a request. +Creates a network interceptor. The returned object can observe requests, replace responses or abort loading. Capabilities depend on the session protocol. -You can enable mocking depending on the URL, headers, or status code. Calling the `mock` method returns a stub object that you can use to modify the response from the web resource. With the stub object, you can return a mock response or abort the request. +- **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. -There are 3 ways to modify the response: +For the Classic setup, see [CDP in Testplane](../../guides/how-to-use-cdp.mdx) and the [CDP interception guide](../../guides/how-to-intercept-requests-and-responses.mdx). The comparison below describes `@testplane/webdriverio` 9.6.2; the runnable example uses BiDi. -- return a custom JSON object (e.g., to mock an API response); -- replace the response with a local file (inject a modified JavaScript file); -- redirect to another URL and return the response from there. +## Usage {/* #usage */} - -The _mock_ command only works when using _Chrome DevTools Protocol (CDP)_. +`await browser.mock(url, filters)` -Read more in the section "[How to use Chrome DevTools Protocol in testplane][how-to-use-cdp]". +## Command parameters {/* #parameters */} -Also, see the recipe "[How to intercept requests and responses][how-to-intercept-requests-and-responses]". +| Parameter | BiDi | Classic/CDP | +| ----------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------- | +| `url` | `URLPattern` string: an absolute HTTP(S) pattern or pathname such as `/api/items`. | Glob string or `RegExp`. | +| `method` | HTTP method string or predicate. | Same. | +| `requestHeaders` | Request-header object or predicate. | Same. | +| `responseHeaders` | Response-header object or predicate. | Not applied. | +| `headers` | Do not use; use `responseHeaders` for responses. | Filters **response headers**, not request headers. | +| `postData` | Not applied. | Request body string or predicate. | +| `statusCode` | Response 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. -## Usage {/* #usage */} +## Result {/* #result */} -```javascript -await browser.mock(url, { method, headers, responseHeaders, postData, statusCode }); -``` +Returns a Promise with a mock object. Shared operations: [respond](../mock/respond.mdx), [respondOnce](../mock/respondOnce.mdx), [abort](../mock/abort.mdx), [abortOnce](../mock/abortOnce.mdx), [waitForResponse](../mock/waitForResponse.mdx), [clear](../mock/clear.mdx) and [restore](../mock/restore.mdx). Signatures can differ between implementations. -## Command Parameters {/* #parameters */} - - - - - - - - - - - - - - -
**Name****Type****Description**
urlStringThe URL of the request to mock.
methodString or FunctionThe HTTP method to filter the resource.
headersObject or FunctionThe request headers to filter the resource.
responseHeadersObject or FunctionThe response headers to filter the resource.
postDataString or FunctionThe request postData to filter the resource.
statusCodeNumber or FunctionThe status code to filter the resource.
- -## Usage Examples {/* #examples */} - -```javascript -it("should mock network resources", async ({ browser }) => { - // use a static string - const userListMock = await browser.mock("**" + "/users/list"); - - // we can also mock responses based on - // request or response headers, status code, or postData - const strictMock = await browser.mock("**", { - // mock all json responses - statusCode: 200, - headers: { "Content-Type": "application/json" }, - responseHeaders: { "Cache-Control": "no-cache" }, - postData: "foobar", - }); +BiDi only: [request](../mock/request.mdx), [requestOnce](../mock/requestOnce.mdx), [redirect](../mock/redirect.mdx), [redirectOnce](../mock/redirectOnce.mdx) and [reset](../mock/reset.mdx). - // comparator function - const apiV1Mock = await browser.mock("**" + "/api/v1", { - statusCode: statusCode => statusCode >= 200 && statusCode <= 203, - headers: headers => - headers["Authorization"] && headers["Authorization"].startsWith("Bearer "), - responseHeaders: headers => headers["Impersonation"], - postData: data => typeof data === "string" && data.includes("foo"), - }); -}); +`mock.calls` stores matching network events, not just completed responses: -it("should modify API responses", async ({ browser }) => { - // filter by method - const todoMock = await browser.mock("**" + "/todos", { - method: "get", - }); +- 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. - // mock the response of the endpoint with predefined fixture - mock.respond([ - { - title: "Injected Todo", - order: null, - completed: false, - url: "http://todo-backend-express-knex.herokuapp.com/916", - }, - ]); - - // respond with a different status code or header - mock.respond( - [ - { - title: "Injected Todo", - order: null, - completed: false, - url: "http://todo-backend-express-knex.herokuapp.com/916", - }, - ], - { - statusCode: 404, - headers: { - "x-custom-header": "foobar", - }, - }, - ); -}); +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`. -it("should modify text assets", async ({ browser }) => { - const scriptMock = await browser.mock("**" + "/script.min.js"); - scriptMock.respond("./tests/fixtures/script.js"); -}); +## Events {/* #events */} + +Subscribe with `mock.on(name, listener)`. Listeners run in Node.js, not in the browser. + +| Event | BiDi | Classic/CDP | +| ----------- | -------------------------------------------------------------- | ------------------------------------------ | +| `request` | `network.beforeRequestSent` event: URL at `event.request.url`. | CDP `Fetch.requestPaused` event. | +| `match` | Not emitted in this version, although declared in types. | Matched response entry. | +| `overwrite` | Request or response event that received an override. | Overridden response parameters. | +| `fail` | Aborted request ID. | Object with `requestId` and `errorReason`. | +| `continue` | Continued request ID. | Continued request ID. | -it("should redirect web resources", async ({ browser }) => { - const headerMock = await browser.mock("**" + "/header.png"); - headerMock.respond("https://media.giphy.com/media/F9hQLAVhWnL56/giphy.gif"); +An event alone is not proof that the entire network exchange has finished. - const pageMock = await browser.mock("https://google.com/"); - pageMock.respond("https://webdriver.io"); - await browser.url("https://google.com"); +## Example {/* #examples */} - console.log(await browser.getTitle()); - // outputs: "WebdriverIO · Next-gen browser and mobile automation test framework for Node.js" +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. + +```javascript testplane=related-mock +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(); + } }); ``` -## Related Commands {/* #related */} - -- [mockClearAll](../mockClearAll) -- [mockRestoreAll](../mockRestoreAll) +## Related commands {/* #related */} -## References +- [mockClearAll](./mockClearAll.mdx) +- [mockRestoreAll](./mockRestoreAll.mdx) +- [respond](../mock/respond.mdx) -We'd like to give credit to the original WebdriverIO docs [article](https://webdriver.io/docs/api/browser/mock), from which we drew some information while writing our version. +## References {/* #references */} -[how-to-use-cdp]: ../../../guides/how-to-use-cdp -[how-to-intercept-requests-and-responses]: ../../../guides/how-to-intercept-requests-and-responses +This page draws on the [original WebdriverIO article](https://webdriver.io/docs/api/browser/mock). diff --git a/docs/commands/browser/restore.mdx b/docs/commands/browser/restore.mdx new file mode 100644 index 00000000..7463ff91 --- /dev/null +++ b/docs/commands/browser/restore.mdx @@ -0,0 +1,53 @@ +# restore + +## Overview {/* #overview */} + +Remove emulation installed by `emulate` on the same browser instance. This command does not restore cookies, storage, network throttling, CPU throttling or mocks. + +## Usage {/* #usage */} + +`await browser.restore()` or `await browser.restore(scopes)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------- | -------------------- | --------------------- | ------------------------------------------------------------------------- | +| `scopes` | `string \| string[]` | All registered scopes | One scope or several: clock, geolocation, userAgent, colorScheme, onLine. | + +## Result {/* #result */} + +`Promise`. With no recorded emulation for the browser instance, the command does nothing. + +## Limitations {/* #limitations */} + +Choose one cleanup method for each emulation: call the function returned by `emulate`, **or** use `browser.restore(scope)` in `finally` in the same test. Do not also call `browser.restore()` for a scope you have already cleaned up: in `@testplane/webdriverio` 9.6.2 it can try to remove the same preload script twice. Reload the page to see the original value if a preload script changed it. + +`device` is not a restore scope. Use the function returned by `emulate("device", name)`. It removes the user-agent override and applies the Desktop Chrome viewport (1280 × 720, DPR 1), not the previous dimensions. + +## 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-restore +const assert = require("node:assert/strict"); + +it("restore: remove a user-agent override", async ({ browser }) => { + await browser.url("/"); + const original = await browser.execute(() => navigator.userAgent); + await browser.emulate("userAgent", "ExampleBrowser/1.0"); + try { + await browser.url("/"); + assert.equal(await browser.execute(() => navigator.userAgent), "ExampleBrowser/1.0"); + } finally { + await browser.restore("userAgent"); + } + await browser.url("/"); + assert.equal(await browser.execute(() => navigator.userAgent), original); +}); +``` + +## See also {/* #see-also */} + +- [emulate](./emulate.mdx) +- [restoreState](./restoreState.mdx) +- [mock.restore](../mock/restore.mdx) diff --git a/docs/commands/browser/setViewport.mdx b/docs/commands/browser/setViewport.mdx new file mode 100644 index 00000000..9b9032c3 --- /dev/null +++ b/docs/commands/browser/setViewport.mdx @@ -0,0 +1,56 @@ +# setViewport + +## Overview {/* #overview */} + +Set the size of the page viewport and its device pixel ratio. Unlike `setWindowSize`, this changes the area used to render the page, not the outer browser window. + +## Usage {/* #usage */} + +`browser.setViewport({ width, height, devicePixelRatio })` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------------ | -------- | ----------- | -------------------------------------------------------- | +| `width` | `number` | Required | Viewport width in CSS pixels. | +| `height` | `number` | Required | Viewport height in CSS pixels. | +| `devicePixelRatio` | `number` | 1 | The device pixel ratio (DPR). Omitting it sets DPR to 1. | + +## Result {/* #result */} + +`Promise`. + +## Limitations {/* #limitations */} + +Requires WebDriver BiDi (`webSocketUrl: true`) and a driver that supports viewport resizing. Run the command in the top-level document. If a test has switched into an iframe, return with [switchFrame(null)](./switchFrame.mdx) first. + +Use integer dimensions in CSS pixels and a positive DPR. In `@testplane/webdriverio` 9.6.2 the client checks width and height against 0 and `Number.MAX_SAFE_INTEGER`; the driver can reject a size within that range. Save both dimensions and DPR if you need to restore them. Changing the viewport does not enable touch input or change the browser engine. + +## 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-set-viewport +const assert = require("node:assert/strict"); + +it("setViewport: change page dimensions", async ({ browser }) => { + await browser.url("/"); + const original = await browser.execute(() => ({ + width: innerWidth, + height: innerHeight, + devicePixelRatio, + })); + try { + await browser.setViewport({ width: 800, height: 600, devicePixelRatio: 2 }); + const viewport = await browser.execute(() => [innerWidth, innerHeight, devicePixelRatio]); + assert.deepEqual(viewport, [800, 600, 2]); + } finally { + await browser.setViewport(original); + } +}); +``` + +## See also {/* #see-also */} + +- [setWindowSize](./setWindowSize.mdx) +- [emulate](./emulate.mdx) diff --git a/docs/commands/browser/switchFrame.mdx b/docs/commands/browser/switchFrame.mdx new file mode 100644 index 00000000..7968d7d2 --- /dev/null +++ b/docs/commands/browser/switchFrame.mdx @@ -0,0 +1,57 @@ +# switchFrame + +## Overview {/* #overview */} + +Switch subsequent browser commands into an iframe, or return to the top-level document. This changes the browsing context, not the selected window. + +## Usage {/* #usage */} + +`browser.switchFrame(context)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------- | --------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `context` | `Element \| string \| Function \| null` | Required | An iframe element; for BiDi, also a context ID, URL, URL substring, or predicate executed in candidate frames. null selects the top-level document. | + +## Result {/* #result */} + +`Promise`. In BiDi mode, returns the selected context ID. In Classic mode, the underlying protocol switch may return no value. + +## Limitations {/* #limitations */} + +Classic supports an iframe element and `null`, but rejects string and function selectors. To switch between sibling frames, first return to the main document with `await browser.switchFrame(null)`, then locate the next iframe. Use `finally` if later steps must run in the main document. A frame that cannot be found causes an error. Do not confuse this command with `switchWindow`. + +:::warning + +In WDIO 9.6.2, the predicate-function branch references a global `browser`. In a standard Testplane test using the `{ browser }` argument, a matching frame is found but the command fails with `browser is not defined`. This was reproduced in a BiDi session. Use an iframe element as shown below; do not introduce a global `browser` to work around the failure. + +::: + +## 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-switch-frame +const assert = require("node:assert/strict"); + +it("switchFrame: enter an iframe and return", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = + '

Main page

'; + }); + try { + await browser.switchFrame(browser.$("#frame")); + assert.equal(await browser.$("p").getText(), "Frame content"); + } finally { + await browser.switchFrame(null); + } + assert.equal(await browser.$("h1").getText(), "Main page"); +}); +``` + +## See also {/* #see-also */} + +- [switchWindow](./switchWindow.mdx) +- [execute](./execute.mdx) diff --git a/docs/commands/browser/throttle.mdx b/docs/commands/browser/throttle.mdx index 18fc624c..d142b0a4 100644 --- a/docs/commands/browser/throttle.mdx +++ b/docs/commands/browser/throttle.mdx @@ -1,73 +1,49 @@ -import Admonition from "@theme/Admonition"; - # throttle ## Overview {/* #overview */} -Use the `throttle` command to simulate different types of network connections for the user. +Deprecated alias of [throttleNetwork](./throttleNetwork.mdx). Limits network throughput through CDP/Puppeteer; it is not equivalent to [emulate("onLine")](./emulate.mdx). Use `throttleNetwork` for new code. -This command allows you to model the behavior of a website or web application under various network bandwidth conditions. +## Usage {/* #usage */} -There are also many presets with ready-made network configuration settings. For example: +`await browser.throttle(profile)` -- offline | online -- GPRS -- Regular2G | Good2G -- Regular3G | Good3G -- Regular4G -- DSL -- WiFi +## Command parameters {/* #parameters */} - -The _throttle_ command only works when using the _Chrome DevTools Protocol (CDP)_. +Parameters match [throttleNetwork](./throttleNetwork.mdx#parameters). Pass a profile name: `offline`, `online`, `GPRS`, `Regular2G`, `Good2G`, `Regular3G`, `Good3G`, `Regular4G`, `DSL`, `WiFi`. Names contain no spaces. -Read more in the section "[How to use Chrome DevTools Protocol in testplane][how-to-use-cdp]". +Or pass an object with `offline` (boolean), `latency` (milliseconds), `downloadThroughput` and `uploadThroughput` (bytes per second, `-1` disables throughput limits). Returns `Promise`. -Also, see the recipe "[How to manage network bandwidth][how-to-manage-network-bandwidth]". +## Limitations {/* #limitations */} - +Requires a browser with CDP/Puppeteer access. The implementation selects the first Puppeteer page: use one tab and `isolation: false` for this example, and navigate first. -## Usage {/* #usage */} +In Testplane 9.3.2 / WDIO 9.6.2 / Chrome 150, the `online` profile did not restore connectivity after `offline`. Set `testsPerSession: 1` to prevent limits leaking into the next test. See [throttleNetwork](./throttleNetwork.mdx#limitations). -```javascript -await browser.throttle({ offline, latency, downloadThroughput, uploadThroughput }); -``` +## Example {/* #examples */} -## Command Parameters {/* #parameters */} - - - - - - - - - - - - -
**Name****Type****Description**
offlineBooleanEnable emulation of a loss of connection.
latencyNumberMinimum latency from the sent request to received response headers, in milliseconds.
downloadThroughputNumberMaximum total download throughput (bytes/sec). _-1_ disables download throttling.
uploadThroughputNumberMaximum total upload throughput (bytes/sec). _-1_ disables upload throttling.
- -## Usage Examples {/* #examples */} - -```javascript -it("should throttle the network", async ({ browser }) => { - // use a preset - await browser.throttle("Regular 3G"); - - // configure the network settings manually - await browser.throttle({ - offline: false, - downloadThroughput: (200 * 1024) / 8, - uploadThroughput: (200 * 1024) / 8, - latency: 20, - }); +Set `baseUrl` to a test HTTP server that returns `200` at the root path. The example uses a new session for each test. + +```javascript testplane=related-throttle +const assert = require("node:assert/strict"); + +it("throttle: use the deprecated alias in an isolated session", async ({ browser }) => { + await browser.url("/"); + await browser.throttle("Good3G"); + const status = await browser.execute( + async () => (await fetch("/?throttled", { cache: "no-store" })).status, + ); + assert.equal(status, 200); }); ``` -## References +## Related commands {/* #related */} + +- [throttleNetwork](./throttleNetwork.mdx) +- [throttleCPU](./throttleCPU.mdx) +- [CDP](../../guides/how-to-use-cdp.mdx) +- [Emulation](../../basic-guides/user-environment-emulation.mdx) -We'd like to give credit to the original WebdriverIO docs [article](https://webdriver.io/docs/api/browser/throttle), from which we drew some information while writing our version. +## References {/* #references */} -[how-to-use-cdp]: ../../../guides/how-to-use-cdp -[how-to-manage-network-bandwidth]: ../../../basic-guides/emulation +This page draws on the [original WebdriverIO article](https://webdriver.io/docs/api/browser/throttle). diff --git a/docs/commands/browser/throttleCPU.mdx b/docs/commands/browser/throttleCPU.mdx new file mode 100644 index 00000000..f636c0e0 --- /dev/null +++ b/docs/commands/browser/throttleCPU.mdx @@ -0,0 +1,49 @@ +# throttleCPU + +## Overview {/* #overview */} + +Apply a CPU slowdown through Chrome DevTools Protocol. Use this to exercise a page under reduced processing speed, not to reproduce a particular physical device. + +## Usage {/* #usage */} + +`browser.throttleCPU(factor)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------- | -------- | ----------- | ---------------------------------------------------------------------- | +| `factor` | `number` | Required | Slowdown factor: 1 disables throttling, 2 requests a twofold slowdown. | + +## Result {/* #result */} + +`Promise`. + +## Limitations {/* #limitations */} + +Requires Chromium and an available Puppeteer/CDP connection. The current implementation targets the first page returned by Puppeteer, not necessarily the active Testplane page. For this example, use one tab, `isolation: false` and `testsPerSession: 1`; a fresh session preserves test isolation. A non-number or an unavailable CDP connection causes an error. Factor 1 requests the normal CPU mode. + +## 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-throttle-cpu +const assert = require("node:assert/strict"); + +it("throttleCPU: run a page with a slower CPU", async ({ browser }) => { + await browser.url("/"); + try { + await browser.throttleCPU(2); + await browser.execute(() => { + document.body.innerHTML = ""; + }); + assert.equal(await browser.$("button").getText(), "Ready"); + } finally { + await browser.throttleCPU(1); + } +}); +``` + +## See also {/* #see-also */} + +- [throttleNetwork](./throttleNetwork.mdx) +- [getPuppeteer](./getPuppeteer.mdx) diff --git a/docs/commands/browser/throttleNetwork.mdx b/docs/commands/browser/throttleNetwork.mdx new file mode 100644 index 00000000..95246094 --- /dev/null +++ b/docs/commands/browser/throttleNetwork.mdx @@ -0,0 +1,71 @@ +# throttleNetwork + +## Overview {/* #overview */} + +Limit network throughput and latency or put a page offline through CDP. This affects actual requests, unlike `emulate("onLine", false)`, which only changes a JavaScript property. + +## Usage {/* #usage */} + +`browser.throttleNetwork(profileOrOptions)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| -------------------- | ------------------ | ------------------ | -------------------------------------------------------------------------------------------- | +| `profileOrOptions` | `string \| object` | Required | A named profile or an object with offline, latency, downloadThroughput and uploadThroughput. | +| `offline` | `boolean` | Required in object | Whether network access is disabled. | +| `latency` | `number` | Required in object | Minimum latency in milliseconds. | +| `downloadThroughput` | `number` | Required in object | Download bytes per second; -1 removes this limit. | +| `uploadThroughput` | `number` | Required in object | Upload bytes per second; -1 removes this limit. | + +## Result {/* #result */} + +`Promise`. + +## Limitations {/* #limitations */} + +The local CDP path requires Chromium and a Puppeteer connection. It targets the first Puppeteer page. Use one tab, `isolation: false` and `testsPerSession: 1` for the example below. Load the page before disabling the network. Profiles: `offline`, `GPRS`, `Regular2G`, `Good2G`, `Regular3G`, `Good3G`, `Regular4G`, `DSL`, `WiFi`, `online`. Unsupported profile names throw an error. Sauce Labs sessions use a separate backend command. + +:::warning + +With Testplane 9.3.2, WDIO 9.6.2 and Chrome for Testing 150.0.7871.124, a subsequent `"online"` call did not restore networking after `"offline"`. Each call creates a separate CDP session. Do not rely on this reset when reusing a browser: the example ends the offline session after the test and checks networking in a new one. To switch modes within one test, use a single CDP session. + +::: + +## 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-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); +}); + +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); +}); +``` + +## See also {/* #see-also */} + +- [throttleCPU](./throttleCPU.mdx) +- [emulate](./emulate.mdx) +- [getPuppeteer](./getPuppeteer.mdx) diff --git a/docs/commands/browser/unstable_captureDomSnapshot.mdx b/docs/commands/browser/unstable_captureDomSnapshot.mdx new file mode 100644 index 00000000..cfa4a41e --- /dev/null +++ b/docs/commands/browser/unstable_captureDomSnapshot.mdx @@ -0,0 +1,81 @@ +# unstable_captureDomSnapshot + +## Overview {/* #overview */} + +Capture a compact textual representation of the current document or a selected subtree for diagnostics. To capture the document with options, pass the options object as the only argument. + +## Usage {/* #usage */} + +`browser.unstable_captureDomSnapshot(selector?, options?)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ----------------------- | ---------- | -------------------------- | ----------------------------------------------------------------------------------------- | +| `selector` | `string` | `body` / `documentElement` | Optional CSS selector selecting the snapshot root. Omit it to start at the document body. | +| `options.includeTags` | `string[]` | `[]` | Remove names from the default excluded-tag set; not an allowlist. | +| `options.excludeTags` | `string[]` | `[]` | Exclude these elements with their subtrees; takes precedence over includeTags. | +| `options.includeAttrs` | `string[]` | `[]` | Add names to the set of retained attributes. | +| `options.excludeAttrs` | `string[]` | `[]` | Remove names from the retained-attribute set; takes precedence over includeAttrs. | +| `options.truncateText` | `boolean` | `true` | Truncate direct text nodes. This flag does not disable attribute-value truncation. | +| `options.maxTextLength` | `number` | `100` | Maximum text or attribute length before adding `...`. | + +## Result {/* #result */} + +`Promise` with four fields: + +- `snapshot`: compact, indented text, not HTML. +- `omittedTags`: sorted names of excluded tags encountered during traversal. +- `omittedAttributes`: sorted names of attributes omitted on retained elements. +- `textWasTruncated`: whether text or an attribute was shortened. + +A missing CSS match returns `snapshot: "# Element not found: "`; invalid CSS returns `"# Invalid selector: "`. These cases do not throw a selector error. These lists are diagnostics of this traversal, not a complete report of every omitted descendant. + +`maxTextLength` does not limit `id`, `class` or state-marker values such as `@value`. Excluded `id` and `class` are not listed in `omittedAttributes`. + +## Limitations {/* #limitations */} + +By default, `head`, `link`, `meta`, `noscript`, `script`, `slot`, `style`, `template` and `title` are excluded. Tag names are case-insensitive. Retained attributes include IDs, classes, form attributes, selected ARIA attributes and test attributes. Other attributes can be added with `includeAttrs`. Hidden retained elements are marked `@hidden`; empty uninformative elements and SVG children may be omitted. This is neither the full DOM nor an accessibility tree. + +The snapshot can contain input values, page text and sensitive attributes. `excludeAttrs` is not a general redaction mechanism: current input values are also recorded as `@value`. Use non-sensitive fixture data and inspect output before attaching it to logs or reports. + +:::warning + +This is an unstable Testplane API. Its signature, behavior and result format may change between versions. + +::: + +## Example {/* #examples */} + +Set `baseUrl` to a local HTTP test site where `/` serves an HTML page. Run the example in a Testplane test file. + +```javascript testplane=testplane-browser-unstable-capture-dom-snapshot +const assert = require("node:assert/strict"); + +it("browser.unstable_captureDomSnapshot: capture a filtered subtree", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = + '

abcdefghijk

Outside

'; + }); + const result = await browser.unstable_captureDomSnapshot("#panel", { + excludeAttrs: ["data-internal"], + maxTextLength: 6, + }); + assert.match(result.snapshot, /section#panel/); + assert.match(result.snapshot, /abcdef\.\.\./); + assert.doesNotMatch(result.snapshot, /Outside|data-internal/); + assert.ok(result.omittedTags.includes("script")); + assert.ok(result.omittedAttributes.includes("data-internal")); + assert.equal(result.textWasTruncated, true); + const missing = await browser.unstable_captureDomSnapshot("#missing"); + assert.equal(missing.snapshot, "# Element not found: #missing"); + const invalid = await browser.unstable_captureDomSnapshot("["); + assert.equal(invalid.snapshot, "# Invalid selector: ["); +}); +``` + +## See also {/* #see-also */} + +- [element.unstable_captureDomSnapshot](../element/unstable_captureDomSnapshot.mdx) +- [execute](./execute.mdx) diff --git a/docs/commands/browser/unstable_getCdp.mdx b/docs/commands/browser/unstable_getCdp.mdx new file mode 100644 index 00000000..0b71ee4e --- /dev/null +++ b/docs/commands/browser/unstable_getCdp.mdx @@ -0,0 +1,49 @@ +# unstable_getCdp + +## Overview {/* #overview */} + +Get Testplane’s existing Chrome DevTools Protocol connection for advanced diagnostics. This is Testplane’s `CDP` object, not a Puppeteer browser or a Puppeteer `CDPSession`. + +## Usage {/* #usage */} + +`browser.unstable_getCdp()` + +## Parameters {/* #parameters */} + +This command has no parameters. + +## Result {/* #result */} + +`Promise`. Returns `null` for a non-Chromium session or when Testplane could not establish its CDP connection. + +## Limitations {/* #limitations */} + +Check for `null` before use. `cdp.request(method, params?, cdpSessionId?)` sends a raw CDP request; page-targeted commands may need an attached target session ID. Domain helpers include `target`, `runtime`, `network`, `page`, `dom`, `css`, `fetch`, `debugger` and `profiler`. Their contracts are also unstable. Do not call `cdp.close()`: Testplane owns and uses this shared connection. Avoid changing domains used by the runner unless you understand the interaction. + +:::warning + +This is an unstable Testplane API. Its signature, behavior and result format may change between versions. + +::: + +## Example {/* #examples */} + +Run this test in a Chromium browser with an available CDP connection. It reads browser version metadata without changing the page or closing the shared connection. + +```javascript testplane=testplane-browser-unstable-get-cdp +const assert = require("node:assert/strict"); + +it("unstable_getCdp: query the connected Chromium browser", async ({ browser }) => { + const cdp = await browser.unstable_getCdp(); + assert.ok(cdp, "This test requires a Chromium session with a CDP connection"); + const version = await cdp.request("Browser.getVersion"); + assert.match(version.product, /Chrome/); + assert.equal(typeof version.protocolVersion, "string"); + // Testplane owns this connection: do not call cdp.close(). +}); +``` + +## See also {/* #see-also */} + +- [getPuppeteer](./getPuppeteer.mdx) +- [execute](./execute.mdx) diff --git a/docs/commands/browser/url.mdx b/docs/commands/browser/url.mdx index 79d45f52..3479e4f7 100644 --- a/docs/commands/browser/url.mdx +++ b/docs/commands/browser/url.mdx @@ -2,62 +2,74 @@ ## Overview {/* #overview */} -Use the `url` command to navigate to the specified URL in the browser. +Opens a URL. In Testplane, omitting the argument or passing an empty string returns the current URL without navigation. Navigating to the same URL again reloads the page. -If [baseUrl][base-url] is specified in the configuration, it will be added to the `url` parameter using the Node.js method [url.resolve()][url-resolve]. - -Calling `browser.url()` with the same URL as before will reload the page. +With [baseUrl](../../reference/config/browsers.mdx#base_url), the address is resolved using `url.resolve(baseUrl, url)`. For `baseUrl` equal to `http://example.com/site/`, `relative` opens `/site/relative`, while `/rootRelative` opens `/rootRelative`. An absolute URL does not depend on `baseUrl`. The trailing `/` in the base address affects relative path resolution. ## Usage {/* #usage */} -```javascript -await browser.url(url); -``` - -## Command Parameters {/* #parameters */} - - - - - - - - - -
**Name****Type****Description**
urlStringThe URL to open.
- -## Usage Examples {/* #examples */} - -**url.js** - -```javascript -// navigate to URL -await browser.url("https://webdriver.io"); - -// get the URL -console.log(await browser.getUrl()); // outputs: "https://webdriver.io" +`await browser.url(url, options)`; `await browser.url()` + +## Command parameters {/* #parameters */} + +| Parameter | Description | +| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `url` | Absolute or relative address string. Omit it to read the current address. | +| `options.wait` | BiDi: `none`, `interactive`, `complete` or `networkIdle`. Defaults to the session page-load strategy; normally `complete`. See the `networkIdle` limitation below. | +| `options.timeout` | BiDi: timeout for `networkIdle` only, default `5000` ms. Does not replace Testplane or page-load timeouts. | +| `options.headers` | BiDi: headers for the navigation request, not persistent headers for every page resource. | +| `options.auth` | BiDi: `{ user, pass }` for HTTP Basic Auth. Replaces `Authorization` from `headers`. Use HTTPS and keep secrets out of test files. | +| `options.onBeforeLoad` | BiDi: function run before the new document scripts. It is serialized and cannot access Node.js closures. | + +## Limitations {/* #limitations */} + +Options apply only to HTTP(S) navigation in BiDi. The Testplane wrapper ignores the second argument in Classic. After successful navigation, the temporary init script is removed; its changes in the loaded document remain until the next navigation. + +In the verified Testplane 9.3.2 / WDIO 9.6.2 / Chrome 150 combination, `networkIdle` fails with `Couldn't find request for navigation with id ...`: the implementation looks up a navigation request using a context ID. Use `complete`, then explicitly wait for the required application state. `complete` alone does not mean that background application requests have finished. + +## Result {/* #result */} + +Without an address, returns the current URL string. Navigation returns `undefined` in Classic; in BiDi it may return navigation request data or `undefined`. To read the address, use `getUrl()` or `url()` without an argument. + +## Example {/* #examples */} + +The example uses Chrome/BiDi and a test HTTP server in `baseUrl`. At `/navigation`, a page script records `window.initialSeed = window.navigationSeed ?? null`, and the server embeds the received `x-example` header in `window.receivedHeader`. The root path serves a regular HTML page. + +```javascript testplane=related-url +const assert = require("node:assert/strict"); + +it("url: navigate with BiDi options and read the current URL", async ({ browser }) => { + await browser.url("/"); + const target = new URL("/navigation", await browser.getUrl()).href; + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + await browser.url(target, { + wait: "complete", + headers: { "x-example": "navigation" }, + onBeforeLoad: () => { + window.navigationSeed = 42; + }, + }); + assert.equal(await browser.url(), target); + assert.deepEqual(await browser.execute(() => [window.initialSeed, window.receivedHeader]), [ + 42, + "navigation", + ]); + await browser.execute(() => { + window.unsavedValue = "temporary"; + }); + await browser.url(target); + assert.equal(await browser.execute(() => typeof window.unsavedValue), "undefined"); + assert.equal(await browser.execute(() => window.initialSeed), null); +}); ``` -**baseUrlResolutions.js** - -```javascript -// Let baseUrl = http://example.com/site/ important to add a slash in the end - -// Specifying a full URL results in https://webdriver.io -await browser.url("https://webdriver.io"); - -// Specifying a URL without a leading slash -// results in the URL relative to the baseUrl: http://example.com/site/relative -await browser.url("relative"); - -// Specifying a URL with a leading slash -// results in the URL relative to the root of baseUrl: http://example.com/rootRelative -await browser.url("/rootRelative"); -``` +## Related commands {/* #related */} -## References +- [addInitScript](./addInitScript.mdx) +- [waitUntil](./waitUntil.mdx) -We'd like to give credit to the original WebdriverIO docs [article](https://webdriver.io/docs/api/browser/url), from which we drew some information while writing our version. +## References {/* #references */} -[base-url]: ../../../reference/config/browsers#base_url -[url-resolve]: https://nodejs.org/api/url.html#urlresolvefrom-to +This page draws on the [original WebdriverIO article](https://webdriver.io/docs/api/browser/url). diff --git a/docs/commands/element/customDollar.mdx b/docs/commands/element/customDollar.mdx new file mode 100644 index 00000000..898cdac4 --- /dev/null +++ b/docs/commands/element/customDollar.mdx @@ -0,0 +1,50 @@ +# custom$ + +## Overview {/* #overview */} + +Find an element with a custom locator strategy, passing the parent element as the final strategy argument. Make the strategy search inside that element to limit its scope. + +## Usage {/* #usage */} + +`element.custom$(strategyName, ...strategyArguments)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------------- | ----------- | ----------- | -------------------------------------------------- | +| `strategyName` | `string` | Required | Name registered with `browser.addLocatorStrategy`. | +| `strategyArguments` | `unknown[]` | [] | Arguments passed before the parent DOM element. | + +## Result {/* #result */} + +An awaitable element object. If the strategy returns an array, only its first element is used. A result without a match has no `elementId`. + +## Limitations {/* #limitations */} + +Register the strategy on the same browser instance. The parent must exist; an unknown strategy or missing parent causes an error. The callback runs in the browser and must return a DOM element or an array of DOM elements. Convert a `NodeList` with `Array.from`. Scoping is the callback’s responsibility: using `document.querySelector` still searches the whole document. This command does not wait for a particular number of children or for visibility. + +## Example {/* #examples */} + +Set `baseUrl` to a local HTTP test site where `/` serves an HTML page. Run the example in a Testplane test file. + +```javascript testplane=element-custom-dollar +const assert = require("node:assert/strict"); + +it("element.custom$: search inside an element", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = + '
'; + }); + browser.addLocatorStrategy("byTestWithin", (value, root) => + root.querySelector(`[data-test="${value}"]`), + ); + const button = await browser.$("#panel").custom$("byTestWithin", "save"); + assert.equal(await button.getText(), "Inside"); +}); +``` + +## See also {/* #see-also */} + +- [addLocatorStrategy](../browser/addLocatorStrategy.mdx) +- [browser.custom$](../browser/customDollar.mdx) diff --git a/docs/commands/element/customDollarDollar.mdx b/docs/commands/element/customDollarDollar.mdx new file mode 100644 index 00000000..051befe0 --- /dev/null +++ b/docs/commands/element/customDollarDollar.mdx @@ -0,0 +1,51 @@ +# custom$$ + +## Overview {/* #overview */} + +Find elements with a custom locator strategy, passing the parent element as the final strategy argument. Make the strategy search inside that element to limit its scope. + +## Usage {/* #usage */} + +`element.custom$$(strategyName, ...strategyArguments)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------------- | ----------- | ----------- | -------------------------------------------------- | +| `strategyName` | `string` | Required | Name registered with `browser.addLocatorStrategy`. | +| `strategyArguments` | `unknown[]` | [] | Arguments passed before the parent DOM element. | + +## Result {/* #result */} + +An awaitable array of element objects. If the strategy finds nothing, the array is empty. + +## Limitations {/* #limitations */} + +Register the strategy on the same browser instance. The parent must exist; an unknown strategy or missing parent causes an error. The callback runs in the browser and must return a DOM element or an array of DOM elements. Convert a `NodeList` with `Array.from`. Scoping is the callback’s responsibility: using `document.querySelector` still searches the whole document. This command does not wait for a particular number of children or for visibility. + +## Example {/* #examples */} + +Set `baseUrl` to a local HTTP test site where `/` serves an HTML page. Run the example in a Testplane test file. + +```javascript testplane=element-custom-dollar-dollar +const assert = require("node:assert/strict"); + +it("element.custom$$: find children with a custom strategy", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = + '

Outside

First

Second

'; + }); + browser.addLocatorStrategy("byTestWithin", (value, root) => + Array.from(root.querySelectorAll(`[data-test="${value}"]`)), + ); + const items = await browser.$("#panel").custom$$("byTestWithin", "item"); + assert.equal(items.length, 2); + assert.equal(await items[1].getText(), "Second"); +}); +``` + +## See also {/* #see-also */} + +- [addLocatorStrategy](../browser/addLocatorStrategy.mdx) +- [browser.custom$$](../browser/customDollarDollar.mdx) diff --git a/docs/commands/element/execute.mdx b/docs/commands/element/execute.mdx new file mode 100644 index 00000000..936e7833 --- /dev/null +++ b/docs/commands/element/execute.mdx @@ -0,0 +1,52 @@ +# execute + +## Overview {/* #overview */} + +Execute JavaScript in the browser with the selected DOM element as the first argument. Use it to inspect or change DOM properties that have no dedicated command. + +## Usage {/* #usage */} + +`element.execute(script, ...args)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------- | -------------------- | ----------- | ---------------------------------------------------- | +| `script` | `Function \| string` | Required | Function, or function body, executed in the browser. | +| `args` | `unknown[]` | [] | Additional arguments after the DOM element. | + +## Result {/* #result */} + +A promise with the serialized function result. The BiDi execution path also awaits a promise returned by the function. + +## Limitations {/* #limitations */} + +The command calls `waitForExist` before execution. Browser code cannot access Node.js variables or imports through closures; pass data as arguments. This does not imply visibility or clickability. The asynchronous example below uses WebDriver BiDi. + +## Example {/* #examples */} + +Set `baseUrl` to a local HTTP test site where `/` serves an HTML page. Run the example in a Testplane test file. + +```javascript testplane=element-execute +const assert = require("node:assert/strict"); + +it("element.execute: pass the DOM element to a browser function", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = '
'; + }); + const result = await browser.$("#counter").execute(async (element, increment) => { + const count = Number(element.dataset.count) + increment; + element.dataset.count = String(count); + return { count, id: element.id }; + }, 3); + assert.deepEqual(result, { count: 7, id: "counter" }); + assert.equal(await browser.$("#counter").getAttribute("data-count"), "7"); +}); +``` + +## See also {/* #see-also */} + +- [browser.execute](../browser/execute.mdx) +- [executeAsync](./executeAsync.mdx) +- [waitForExist](./waitForExist.mdx) diff --git a/docs/commands/element/executeAsync.mdx b/docs/commands/element/executeAsync.mdx new file mode 100644 index 00000000..f0e65348 --- /dev/null +++ b/docs/commands/element/executeAsync.mdx @@ -0,0 +1,56 @@ +# executeAsync + +## Overview {/* #overview */} + +Execute a callback-based browser script with the DOM element as its first argument. The final argument is a callback that sends one result back to the test. + +## Usage {/* #usage */} + +`element.executeAsync(script, ...args)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------- | -------------------- | ----------- | ------------------------------------------------------------- | +| `script` | `Function \| string` | Required | Function or function body. Call the final callback to finish. | +| `args` | `unknown[]` | [] | Arguments between the DOM element and callback. | + +## Result {/* #result */} + +A promise with the value passed to the callback. Returning a value from the script is not a substitute for calling the callback. + +## Limitations {/* #limitations */} + +Unlike `element.execute`, this implementation does not explicitly call `waitForExist`; wait for the element yourself. For Classic sessions, the protocol script timeout is set with `browser.setTimeout({ script: milliseconds })`. The BiDi path uses `script.callFunction` and does not implement a separate callback timer: do not rely on the Classic timeout to stop a missing callback there. Always call the callback, and keep a finite Testplane `testTimeout`. + +:::warning + +Deprecated in the bundled WebdriverIO API. For new BiDi tests, prefer `element.execute` with an async function. + +::: + +## Example {/* #examples */} + +Set `baseUrl` to a local HTTP test site where `/` serves an HTML page. Run the example in a Testplane test file. + +```javascript testplane=element-execute-async +const assert = require("node:assert/strict"); + +it("element.executeAsync: return data through the final callback", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = '

Ready

'; + }); + const element = await browser.$("#message"); + await element.waitForExist(); + const result = await element.executeAsync((node, prefix, done) => { + setTimeout(() => done(prefix + node.textContent), 20); + }, "Status: "); + assert.equal(result, "Status: Ready"); +}); +``` + +## See also {/* #see-also */} + +- [execute](./execute.mdx) +- [setTimeout](../browser/setTimeout.mdx) diff --git a/docs/commands/element/getElement.mdx b/docs/commands/element/getElement.mdx new file mode 100644 index 00000000..78f91347 --- /dev/null +++ b/docs/commands/element/getElement.mdx @@ -0,0 +1,45 @@ +# getElement + +## Overview {/* #overview */} + +Resolve a chainable element reference into its element object to read properties such as `selector` and `elementId`. + +## Usage {/* #usage */} + +`element.getElement()` + +## Parameters {/* #parameters */} + +This command has no parameters. + +## Result {/* #result */} + +`Promise`: the current element object, including its methods and metadata. + +## Limitations {/* #limitations */} + +This is not a new protocol search, a DOM snapshot or a wait for visibility. The wrapper returns the current element object; do not assume that an `elementId` remains valid after navigation or DOM replacement. + +## Example {/* #examples */} + +Set `baseUrl` to a local HTTP test site where `/` serves an HTML page. Run the example in a Testplane test file. + +```javascript testplane=element-get-element +const assert = require("node:assert/strict"); + +it("getElement: inspect a resolved element object", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = ''; + }); + const element = await browser.$("#save").getElement(); + assert.equal(element.selector, "#save"); + assert.equal(typeof element.elementId, "string"); + assert.equal(await element.getText(), "Save"); +}); +``` + +## See also {/* #see-also */} + +- [$](../browser/$.mdx) +- [isExisting](./isExisting.mdx) diff --git a/docs/commands/element/isStable.mdx b/docs/commands/element/isStable.mdx new file mode 100644 index 00000000..7f6b2efb --- /dev/null +++ b/docs/commands/element/isStable.mdx @@ -0,0 +1,57 @@ +# isStable + +## Overview {/* #overview */} + +Check whether the element’s bounding rectangle stays unchanged across two animation frames. Use the result to detect geometric movement, not arbitrary page activity. + +## Usage {/* #usage */} + +`element.isStable()` + +## Parameters {/* #parameters */} + +This command has no parameters. + +## Result {/* #result */} + +`Promise`: `true` when the compared bounding-rectangle properties are equal; otherwise `false`. + +## Limitations {/* #limitations */} + +Use an existing element in the active tab. A hidden document causes an error because animation frames do not run normally there. Opacity, colors and network activity can change without affecting geometry. A `true` result is a measurement at this moment, not a guarantee that all animations have finished. + +## Example {/* #examples */} + +Set `baseUrl` to a local HTTP test site where `/` serves an HTML page. Run the example in a Testplane test file. + +```javascript testplane=element-is-stable +const assert = require("node:assert/strict"); + +it("isStable: check whether element geometry changes", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = '
Box
'; + }); + const box = await browser.$("#box"); + await box.waitForExist(); + assert.equal(await box.isStable(), true); + await box.execute(node => { + node.animate([{ transform: "translateX(0)" }, { transform: "translateX(200px)" }], { + duration: 500, + iterations: Infinity, + direction: "alternate", + }); + }); + try { + assert.equal(await box.isStable(), false); + } finally { + await box.execute(node => node.getAnimations().forEach(animation => animation.cancel())); + } + assert.equal(await box.isStable(), true); +}); +``` + +## See also {/* #see-also */} + +- [waitForStable](./waitForStable.mdx) +- [waitForExist](./waitForExist.mdx) diff --git a/docs/commands/element/unstable_captureDomSnapshot.mdx b/docs/commands/element/unstable_captureDomSnapshot.mdx new file mode 100644 index 00000000..b4dc36a6 --- /dev/null +++ b/docs/commands/element/unstable_captureDomSnapshot.mdx @@ -0,0 +1,55 @@ +# unstable_captureDomSnapshot + +## Overview {/* #overview */} + +Capture a compact DOM snapshot rooted at the selected element. Content outside that element is not included. + +## Usage {/* #usage */} + +`element.unstable_captureDomSnapshot(options?)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------- | ------------------------ | ----------- | ----------------------------------------------------------------- | +| `options` | `CaptureSnapshotOptions` | `{}` | The same filtering and truncation options as the browser command. | + +## Result {/* #result */} + +`Promise` with `snapshot`, `omittedTags`, `omittedAttributes` and `textWasTruncated`. See the [shared result contract](../browser/unstable_captureDomSnapshot.mdx#result). + +## Limitations {/* #limitations */} + +Uses `element.execute`, including its wait for the element to exist. Filtering, truncation and privacy limitations are the same as for the [browser command](../browser/unstable_captureDomSnapshot.mdx#limitations). In particular, `truncateText: false` does not disable attribute truncation, and input values are not sanitized. This method takes options, not another CSS selector. + +:::warning + +This is an unstable Testplane API. Its signature, behavior and result format may change between versions. + +::: + +## Example {/* #examples */} + +Set `baseUrl` to a local HTTP test site where `/` serves an HTML page. Run the example in a Testplane test file. + +```javascript testplane=testplane-element-unstable-capture-dom-snapshot +const assert = require("node:assert/strict"); + +it("element.unstable_captureDomSnapshot: capture only this element", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = + '

Outside

'; + }); + const result = await browser.$("#panel").unstable_captureDomSnapshot({ truncateText: false }); + assert.match(result.snapshot, /section#panel/); + assert.match(result.snapshot, /button\[data-test=save\] "Save"/); + assert.doesNotMatch(result.snapshot, /Outside/); + assert.equal(result.textWasTruncated, false); +}); +``` + +## See also {/* #see-also */} + +- [browser.unstable_captureDomSnapshot](../browser/unstable_captureDomSnapshot.mdx) +- [execute](./execute.mdx) diff --git a/docs/commands/element/waitForStable.mdx b/docs/commands/element/waitForStable.mdx new file mode 100644 index 00000000..33d4a608 --- /dev/null +++ b/docs/commands/element/waitForStable.mdx @@ -0,0 +1,54 @@ +# waitForStable + +## Overview {/* #overview */} + +Poll `isStable` until the element stops changing geometry, or starts changing when `reverse` is enabled. + +## Usage {/* #usage */} + +`element.waitForStable({ timeout, interval, reverse, timeoutMsg })` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------- | --------- | ----------------------- | -------------------------------------- | +| `timeout` | `number` | `waitTimeout` (3000 ms) | Maximum wait in milliseconds. | +| `interval` | `number` | `waitInterval` (500 ms) | Polling interval in milliseconds. | +| `reverse` | `boolean` | `false` | Wait for `isStable()` to return false. | +| `timeoutMsg` | `string` | — | Custom timeout error message. | + +## Result {/* #result */} + +`Promise`. Successful completion returns `undefined`, not `true`. A timeout or a stability-check error rejects the promise. + +## Limitations {/* #limitations */} + +The default timings come from the browser’s Testplane configuration. All `isStable` limitations apply, including active-tab and geometry-only checks. Wait for the element to exist first when it may be added later. This command does not wait for pending HTTP requests or non-geometric animations. + +## Example {/* #examples */} + +Set `baseUrl` to a local HTTP test site where `/` serves an HTML page. Run the example in a Testplane test file. + +```javascript testplane=element-wait-for-stable +const assert = require("node:assert/strict"); + +it("waitForStable: wait for a size animation to stop", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = '
Box
'; + }); + const box = await browser.$("#box"); + await box.execute(node => { + node.animate([{ width: "40px" }, { width: "140px" }], { duration: 500, fill: "forwards" }); + }); + const result = await box.waitForStable({ timeout: 3000, interval: 50 }); + assert.equal(result, undefined); + assert.equal(await box.execute(node => node.getBoundingClientRect().width), 140); +}); +``` + +## See also {/* #see-also */} + +- [isStable](./isStable.mdx) +- [waitForExist](./waitForExist.mdx) +- [waitUntil](../browser/waitUntil.mdx) diff --git a/docs/commands/mock/abort.mdx b/docs/commands/mock/abort.mdx index 1d0888fd..e6ed5865 100644 --- a/docs/commands/mock/abort.mdx +++ b/docs/commands/mock/abort.mdx @@ -2,51 +2,60 @@ ## Overview {/* #overview */} -Use the `abort` command to abort a request with a specified error. +Aborts matching requests while the rule is active. BiDi and Classic/CDP signatures differ. Do not pass an error-code string in BiDi: it does not select a network error and may change whether the rule is one-shot. -A request can be aborted with one of the following errors: +## Usage {/* #usage */} -- Failed -- Aborted -- TimedOut -- AccessDenied -- ConnectionClosed | ConnectionReset | ConnectionRefused | ConnectionAborted | ConnectionFailed -- NameNotResolved -- InternetDisconnected -- AddressUnreachable -- BlockedByClient | BlockedByResponse +**BiDi:** `mock.abort(once = false)` -## Usage {/* #usage */} +**Classic/CDP:** `mock.abort(errorReason, sticky = true)` -```javascript -mock.abort(errorCode); -``` +## Parameters and result {/* #parameters */} + +BiDi: `once` is a boolean, default `false`; use [abortOnce](./abortOnce.mdx) for one request. Classic/CDP: `errorReason` selects the error; `sticky` defaults to `true` to retain the rule. + +Classic/CDP error codes: `Failed`, `Aborted`, `TimedOut`, `AccessDenied`, `ConnectionClosed`, `ConnectionReset`, `ConnectionRefused`, `ConnectionAborted`, `ConnectionFailed`, `NameNotResolved`, `InternetDisconnected`, `AddressUnreachable`, `BlockedByClient`, `BlockedByResponse`. -## Command Parameters {/* #parameters */} +BiDi synchronously returns the same mock; Classic/CDP has no useful return value. BiDi rules share a queue with [request](./request.mdx) and [redirect](./redirect.mdx). A persistent rule replaces the queue; a one-shot rule retains other one-shot rules and removes the persistent rule. CDP appends rules: an earlier persistent rule can prevent a later rule from being used. - - - - - - +## Example {/* #examples */} - -
**Name****Type****Description**
errorCodeErrorCodeThe response error code. Possible values are listed [above](#overview).
+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. -## Usage Examples {/* #examples */} +```javascript testplane=related-abort +const assert = require("node:assert/strict"); -```javascript -it("should block Google Analytics from page", async ({ browser }) => { - const mock = await browser.mock("https://www.google-analytics.com/**"); - mock.abort("Failed"); +it("mock.abort: block matching BiDi requests", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.abort(); + for (let i = 0; i < 2; i++) { + const failed = await browser.execute(async () => { + try { + await fetch("/api/items", { cache: "no-store" }); + return false; + } catch { + return true; + } + }); + assert.equal(failed, true); + } + } finally { + await mock.restore(); + } }); ``` -## Related Commands {/* #related */} +## Related commands {/* #related */} -- [abortOnce](../abortOnce) +- [abortOnce](./abortOnce.mdx) +- [restore](./restore.mdx) +- [browser.mock](../browser/mock.mdx) -## References +## References {/* #references */} -We'd like to give credit to the original WebdriverIO docs [article](https://webdriver.io/docs/api/mock/abort), from which we drew some information while writing our version. +This page draws on the [original WebdriverIO article](https://webdriver.io/docs/api/mock/abort). diff --git a/docs/commands/mock/abortOnce.mdx b/docs/commands/mock/abortOnce.mdx index 03adb03d..d8431185 100644 --- a/docs/commands/mock/abortOnce.mdx +++ b/docs/commands/mock/abortOnce.mdx @@ -2,60 +2,62 @@ ## Overview {/* #overview */} -Use the `abortOnce` command to abort a request once with a specified error. - -A request can be aborted with one of the following errors: - -- Failed -- Aborted -- TimedOut -- AccessDenied -- ConnectionClosed | ConnectionReset | ConnectionRefused | ConnectionAborted | ConnectionFailed -- NameNotResolved -- InternetDisconnected -- AddressUnreachable -- BlockedByClient | BlockedByResponse +Aborts the next matching request. In BiDi, call `abortOnce()` with no arguments; extra arguments do not select an error or change the one-shot behavior. In Classic/CDP, pass an `errorReason`. ## Usage {/* #usage */} -```javascript -mock.abortOnce(errorCode); -``` - -## Command Parameters {/* #parameters */} - - - - - - - - - -
**Name****Type****Description**
errorCodeErrorCodeThe response error code. Possible values are listed [above](#overview).
- -## Usage Examples {/* #examples */} - -```javascript -it("should block mock only once", async ({ browser }) => { - const mock = await browser.mock("https://webdriver.io"); - mock.abortOnce("Failed"); - - await browser - .url("https://webdriver.io") - // catch exception as the request to the page will fail - .catch(() => console.log('Failed to get the page "https://webdriver.io"')); - - await browser.url("https://webdriver.io"); - console.log(await browser.getTitle()); - // will output: "WebdriverIO · Next-gen browser and mobile automation test framework for Node.js" +**BiDi:** `mock.abortOnce()` + +**Classic/CDP:** `mock.abortOnce(errorReason)` + +## Parameters and result {/* #parameters */} + +BiDi takes no arguments. Classic/CDP requires `errorReason`. + +Classic/CDP error codes: `Failed`, `Aborted`, `TimedOut`, `AccessDenied`, `ConnectionClosed`, `ConnectionReset`, `ConnectionRefused`, `ConnectionAborted`, `ConnectionFailed`, `NameNotResolved`, `InternetDisconnected`, `AddressUnreachable`, `BlockedByClient`, `BlockedByResponse`. + +BiDi synchronously returns the same mock; Classic/CDP has no useful return value. BiDi rules share a queue with [request](./request.mdx) and [redirect](./redirect.mdx). A persistent rule replaces the queue; a one-shot rule retains other one-shot rules and removes the persistent rule. CDP appends rules: an earlier persistent rule can prevent a later rule from being used. + +## Example {/* #examples */} + +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. + +```javascript testplane=related-abort-once +const assert = require("node:assert/strict"); + +it("mock.abortOnce: block one BiDi request", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.abortOnce(); + const failed = await browser.execute(async () => { + try { + await fetch("/api/items", { cache: "no-store" }); + return false; + } catch { + return true; + } + }); + assert.equal(failed, true); + const status = await browser.execute( + async () => (await fetch("/api/items", { cache: "no-store" })).status, + ); + assert.equal(status, 200); + } finally { + await mock.restore(); + } }); ``` -## Related Commands {/* #related */} +## Related commands {/* #related */} -- [abort](../abort) +- [abort](./abort.mdx) +- [restore](./restore.mdx) +- [browser.mock](../browser/mock.mdx) -## References +## References {/* #references */} -We'd like to give credit to the original WebdriverIO docs [article](https://webdriver.io/docs/api/mock/abortOnce), from which we drew some information while writing our version. +This page draws on the [original WebdriverIO article](https://webdriver.io/docs/api/mock/abortOnce). diff --git a/docs/commands/mock/clear.mdx b/docs/commands/mock/clear.mdx index ec1653da..ba005d87 100644 --- a/docs/commands/mock/clear.mdx +++ b/docs/commands/mock/clear.mdx @@ -2,31 +2,56 @@ ## Overview {/* #overview */} -Use the `clear` command to reset all information stored in the `mock.calls` array. +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](./reset.mdx); to remove the interceptor, use [restore](./restore.mdx). ## Usage {/* #usage */} -```javascript -mock.clear(); -``` - -## Usage Examples {/* #examples */} - -```javascript -it("should clear mock", async ({ browser }) => { - const mock = await browser.mock("https://google.com/"); - await browser.url("https://google.com"); - - console.log(mock.calls.length); // outputs: 1 - mock.clear(); - console.log(mock.calls.length); // outputs: 0 +`await mock.clear()` + +## Parameters and result {/* #parameters */} + +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](./waitForResponse.mdx) when waiting for a new response rather than a previously recorded one. + +## Example {/* #examples */} + +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. + +```javascript testplane=related-clear +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(); + } }); ``` -## Related Commands {/* #related */} +## Related commands {/* #related */} -- [restore](../restore) +- [reset](./reset.mdx) +- [restore](./restore.mdx) +- [browser.mock](../browser/mock.mdx) -## References +## References {/* #references */} -We'd like to give credit to the original WebdriverIO docs [article](https://webdriver.io/docs/api/mock/clear), from which we drew some information while writing our version. +This page draws on the [original WebdriverIO article](https://webdriver.io/docs/api/mock/clear). diff --git a/docs/commands/mock/redirect.mdx b/docs/commands/mock/redirect.mdx new file mode 100644 index 00000000..d5d8c551 --- /dev/null +++ b/docs/commands/mock/redirect.mdx @@ -0,0 +1,60 @@ +# redirect + +## Overview {/* #overview */} + +Change the destination URL of matching outgoing requests. This is a request URL override, not an HTTP 3xx response or a browser navigation. + +## Usage {/* #usage */} + +`mock.redirect(redirectUrl, once = false)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------- | --------- | ----------- | ---------------------------------------- | +| `redirectUrl` | `string` | Required | Absolute destination URL. | +| `once` | `boolean` | `false` | Apply only to the next matching request. | + +## Result {/* #result */} + +The same mock object, synchronously. + +## Limitations {/* #limitations */} + +Requires a WebDriver BiDi session (`webSocketUrl: true`); this method is not provided by the Classic/CDP mock implementation. The examples explicitly subscribe to network events in every session; see [the subscription limitation](./waitForResponse.mdx#limitations). Always call `mock.restore()` in `finally` when the mock is no longer needed. + +The destination must be reachable. Redirects use the same queue as `request` and `abort`; installing a persistent redirect replaces that queue, and a one-shot redirect discards a previous persistent rule. After a one-shot rule is consumed, the unmodified request is sent unless another one-shot rule is queued. + +## Example {/* #examples */} + +Use the [local example site](../overview.mdx#run-examples) as `baseUrl`. Both requests for `/api/items` must reach `/api/other`, which returns JSON with `source: "redirected"`. + +```javascript testplane=mock-redirect +const assert = require("node:assert/strict"); + +it("mock.redirect: send matching requests to another endpoint", async ({ browser }) => { + await browser.url("/"); + const target = new URL("/api/other", await browser.getUrl()).href; + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.redirect(target); + for (let i = 0; i < 2; i++) { + const data = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(data.source, "redirected"); + } + } finally { + await mock.restore(); + } +}); +``` + +## See also {/* #see-also */} + +- [redirectOnce](./redirectOnce.mdx) +- [request](./request.mdx) +- [reset](./reset.mdx) diff --git a/docs/commands/mock/redirectOnce.mdx b/docs/commands/mock/redirectOnce.mdx new file mode 100644 index 00000000..e50cd01f --- /dev/null +++ b/docs/commands/mock/redirectOnce.mdx @@ -0,0 +1,61 @@ +# redirectOnce + +## Overview {/* #overview */} + +Send only the next matching request to another URL. Equivalent to `mock.redirect(redirectUrl, true)`. + +## Usage {/* #usage */} + +`mock.redirectOnce(redirectUrl)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------- | -------- | ----------- | ------------------------- | +| `redirectUrl` | `string` | Required | Absolute destination URL. | + +## Result {/* #result */} + +The same mock object, synchronously. + +## Limitations {/* #limitations */} + +Requires a WebDriver BiDi session (`webSocketUrl: true`); this method is not provided by the Classic/CDP mock implementation. The examples explicitly subscribe to network events in every session; see [the subscription limitation](./waitForResponse.mdx#limitations). Always call `mock.restore()` in `finally` when the mock is no longer needed. + +The destination must be reachable. Redirects use the same queue as `request` and `abort`; installing a persistent redirect replaces that queue, and a one-shot redirect discards a previous persistent rule. After a one-shot rule is consumed, the unmodified request is sent unless another one-shot rule is queued. + +## Example {/* #examples */} + +Use the [local example site](../overview.mdx#run-examples) as `baseUrl`. `/api/items` returns JSON with `source: "original"`; `/api/other` returns `source: "redirected"`. Only the first request should reach `/api/other`. + +```javascript testplane=mock-redirect-once +const assert = require("node:assert/strict"); + +it("mock.redirectOnce: redirect only the next request", async ({ browser }) => { + await browser.url("/"); + const target = new URL("/api/other", await browser.getUrl()).href; + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.redirectOnce(target); + const first = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + const second = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(first.source, "redirected"); + assert.equal(second.source, "original"); + } finally { + await mock.restore(); + } +}); +``` + +## See also {/* #see-also */} + +- [redirect](./redirect.mdx) +- [request](./request.mdx) +- [reset](./reset.mdx) diff --git a/docs/commands/mock/request.mdx b/docs/commands/mock/request.mdx new file mode 100644 index 00000000..afb022a2 --- /dev/null +++ b/docs/commands/mock/request.mdx @@ -0,0 +1,65 @@ +# request + +## Overview {/* #overview */} + +Override matching outgoing requests before they reach the server. Use this to change headers, the method, body, cookies or target URL. + +## Usage {/* #usage */} + +`mock.request(overwrite, once = false)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------------- | ------------------------------------ | ----------- | ------------------------------------------------------------------------------------------------------- | +| `overwrite` | `object` | Required | Request fields to override. | +| `overwrite.body` | `unknown \| Function` | — | Request body; strings are sent as text, objects as JSON. Falsy body values are ignored in this version. | +| `overwrite.cookies` | `Cookie[] \| Function` | — | Cookie list in WebDriver cookie format. | +| `overwrite.headers` | `Record \| Function` | — | Replacement header map, not a merge with the original headers. | +| `overwrite.method` | `string \| Function` | — | HTTP method, for example `POST`. | +| `overwrite.url` | `string \| Function` | — | Absolute replacement URL. | +| `once` | `boolean` | `false` | Apply the rule only to the next matching request. | + +## Result {/* #result */} + +The same mock object, synchronously, for chaining. + +## Limitations {/* #limitations */} + +Requires a WebDriver BiDi session (`webSocketUrl: true`); this method is not provided by the Classic/CDP mock implementation. The examples explicitly subscribe to network events in every session; see [the subscription limitation](./waitForResponse.mdx#limitations). Always call `mock.restore()` in `finally` when the mock is no longer needed. + +The override affects outgoing requests; it does not fabricate responses. Each field may be a value or a synchronous function receiving the BiDi request event (the URL is in `event.request.url`). Request overrides, redirects and aborts share one rule queue. A persistent rule replaces that queue; a one-shot rule keeps existing one-shot rules but removes a persistent rule. Do not expect a persistent rule to resume after a one-shot rule. + +## Example {/* #examples */} + +Use the [local example site](../overview.mdx#run-examples) as `baseUrl`. `/api/items` accepts GET and POST and returns the received HTTP method in the JSON field `method` and the `x-example` header in `header`. Both requests should reach the server with the override. + +```javascript testplane=mock-request +const assert = require("node:assert/strict"); + +it("mock.request: change outgoing requests", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.request({ method: "POST", headers: { "x-example": "persistent" } }); + for (let i = 0; i < 2; i++) { + const data = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(data.method, "POST"); + assert.equal(data.header, "persistent"); + } + } finally { + await mock.restore(); + } +}); +``` + +## See also {/* #see-also */} + +- [requestOnce](./requestOnce.mdx) +- [respond](./respond.mdx) +- [reset](./reset.mdx) diff --git a/docs/commands/mock/requestOnce.mdx b/docs/commands/mock/requestOnce.mdx new file mode 100644 index 00000000..f55c02e8 --- /dev/null +++ b/docs/commands/mock/requestOnce.mdx @@ -0,0 +1,65 @@ +# requestOnce + +## Overview {/* #overview */} + +Override only the next matching outgoing request. Equivalent to `mock.request(overwrite, true)`. + +## Usage {/* #usage */} + +`mock.requestOnce(overwrite)` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------------- | ------------------------------------ | ----------- | ------------------------------------------------------------------------------------------------------- | +| `overwrite` | `object` | Required | Request fields to override. | +| `overwrite.body` | `unknown \| Function` | — | Request body; strings are sent as text, objects as JSON. Falsy body values are ignored in this version. | +| `overwrite.cookies` | `Cookie[] \| Function` | — | Cookie list in WebDriver cookie format. | +| `overwrite.headers` | `Record \| Function` | — | Replacement header map, not a merge with the original headers. | +| `overwrite.method` | `string \| Function` | — | HTTP method, for example `POST`. | +| `overwrite.url` | `string \| Function` | — | Absolute replacement URL. | + +## Result {/* #result */} + +The same mock object, synchronously, for chaining. + +## Limitations {/* #limitations */} + +Requires a WebDriver BiDi session (`webSocketUrl: true`); this method is not provided by the Classic/CDP mock implementation. The examples explicitly subscribe to network events in every session; see [the subscription limitation](./waitForResponse.mdx#limitations). Always call `mock.restore()` in `finally` when the mock is no longer needed. + +The override affects outgoing requests; it does not fabricate responses. Each field may be a value or a synchronous function receiving the BiDi request event (the URL is in `event.request.url`). Request overrides, redirects and aborts share one rule queue. A persistent rule replaces that queue; a one-shot rule keeps existing one-shot rules but removes a persistent rule. Do not expect a persistent rule to resume after a one-shot rule. + +## Example {/* #examples */} + +Use the [local example site](../overview.mdx#run-examples) as `baseUrl`. `/api/items` returns the received `x-example` header in the JSON field `header`, or `null` if it is absent. Only the first request should contain the header. + +```javascript testplane=mock-request-once +const assert = require("node:assert/strict"); + +it("mock.requestOnce: change only the next request", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.requestOnce({ headers: { "x-example": "once" } }); + const first = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + const second = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(first.header, "once"); + assert.equal(second.header, null); + } finally { + await mock.restore(); + } +}); +``` + +## See also {/* #see-also */} + +- [request](./request.mdx) +- [respond](./respond.mdx) +- [reset](./reset.mdx) diff --git a/docs/commands/mock/reset.mdx b/docs/commands/mock/reset.mdx new file mode 100644 index 00000000..bb0c0cce --- /dev/null +++ b/docs/commands/mock/reset.mdx @@ -0,0 +1,74 @@ +# reset + +## Overview {/* #overview */} + +Clear recorded calls and all request and response override rules while keeping the mock’s interception active. Use it to reuse the mock with its original URL pattern and filters. + +## Usage {/* #usage */} + +`mock.reset()` + +## Parameters {/* #parameters */} + +This command has no parameters. + +## Result {/* #result */} + +The same mock object, synchronously. + +## Limitations {/* #limitations */} + +Requires a WebDriver BiDi session (`webSocketUrl: true`); this method is not provided by the Classic/CDP mock implementation. The examples explicitly subscribe to network events in every session; see [the subscription limitation](./waitForResponse.mdx#limitations). Always call `mock.restore()` in `finally` when the mock is no longer needed. + +`clear()` removes only history and preserves rules. `reset()` also removes rules, including redirects and aborts. `restore()` removes interception and makes the mock unusable for new overrides. Reset does not undo a request already sent or a response already delivered. + +## Example {/* #examples */} + +Use the [local example site](../overview.mdx#run-examples) as `baseUrl`. `/api/items` returns JSON with `source: "original"` and the received `x-example` header in `header` (`null` if absent). The test resets the same mock between requests. + +```javascript testplane=mock-reset +const assert = require("node:assert/strict"); + +it("mock.reset: remove overrides but keep the mock usable", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.request({ headers: { "x-example": "overridden" } }); + const first = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(first.header, "overridden"); + await mock.waitForResponse({ timeout: 3000 }); + assert.equal(mock.reset(), mock); + assert.equal(mock.calls.length, 0); + const second = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(second.header, null); + await mock.waitForResponse({ timeout: 3000 }); + assert.equal(mock.calls.length, 1); + mock.respond({ source: "mocked" }); + const third = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(third.source, "mocked"); + mock.reset(); + const fourth = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(fourth.source, "original"); + } finally { + await mock.restore(); + } +}); +``` + +## See also {/* #see-also */} + +- [clear](./clear.mdx) +- [restore](./restore.mdx) +- [request](./request.mdx) +- [respond](./respond.mdx) diff --git a/docs/commands/mock/respond.mdx b/docs/commands/mock/respond.mdx index b403d334..63ea617e 100644 --- a/docs/commands/mock/respond.mdx +++ b/docs/commands/mock/respond.mdx @@ -1,100 +1,96 @@ -import Admonition from "@theme/Admonition"; - # respond ## Overview {/* #overview */} -Use the `respond` command to always reply with the same overwrite. - - - Also read the recipe "[How to Track and Intercept Network Requests and - Responses][how-to-intercept-requests-and-responses]". - +Overrides responses to matching requests while the rule is active. BiDi still sends the original request to the server; this is not a way to prevent request side effects. ## Usage {/* #usage */} -```javascript -mock.respond(overwrites, { header, statusCode, fetchResponse }); -``` +`mock.respond(overwrites, params)` -## Command Parameters {/* #parameters */} +## Command parameters {/* #parameters */} - - - - - - - - - +| Parameter | BiDi | Classic/CDP | +| ---------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +| `overwrites` | Body string or JSON object/array. Body callbacks are not supported. | String, JSON or function receiving the request entry and client. The function may return a Promise. | +| `params.headers` | Response-header object or synchronous function of the response event. Replaces the header set. | Object or function. Adds to original headers. | +| `params.statusCode` | Number or synchronous function of the response event. | Number or function. | +| `params.cookies` | WebDriver-format `Cookie[]` or synchronous function of the response event. | Not supported by this implementation. | +| `params.fetchResponse` | Not applied: overrides happen at the response stage, so the request reaches the server. | Boolean, default `true`. `false` overrides before the original body is fetched. | - -
**Name****Type****Description**
overwritesMockOverwrite_Payload_ to overwrite the response.
headerObjectOverwrite specific headers.
statusCodeNumberOverwrite the response status code.
fetchResponseBooleanFetch the actual response before replying with fake data.
+For `params.cookies`, use a string `value`. If you set an expiration time, use `expiry` (Unix time in seconds), not `expires`. In the tested Chrome 150 BiDi session, the command accepted this option but the cookie was not stored. To set a cookie in that configuration, send a `Set-Cookie` response header as in the example. Restoring the mock does not remove cookies from the browser. -## Usage Examples {/* #examples */} +The parameter is **`headers`**, not `header`. Metadata defaults to the original values when not overridden. -```javascript -it("should demonstrate response overwrite with static data", async ({ browser }) => { - const mock = await browser.mock("https://todo-backend-express-knex.herokuapp.com/", { - method: "get", - }); +## Limitations {/* #limitations */} - mock.respond( - [ - { - title: "Injected (non) completed Todo", - order: null, - completed: false, - }, +In BiDi (`@testplane/webdriverio` 9.6.2), `mock.respond("")` leaves the original body in place; it does not produce an empty response. A nonempty file path or URL string is sent as response text. It does not read a file or redirect the request; use [redirect](./redirect.mdx) to change the URL. In Classic/CDP, an existing path is read as a local file, while an HTTP(S) URL string creates a redirect response. + +Do not mix persistent and one-shot rules without accounting for the implementation. In BiDi, `respond()` replaces the response queue with a persistent rule. `respondOnce()` removes a persistent rule and appends to other one-shot rules. CDP appends rules, so an earlier persistent rule can mask later ones. + +## Result {/* #result */} + +BiDi synchronously returns the same mock. Classic/CDP has no useful return value. Call `await mock.restore()` to remove overrides and the interceptor. + +## Example {/* #examples */} + +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. + +```javascript testplane=related-respond +const assert = require("node:assert/strict"); + +it("mock.respond: replace response data and metadata in BiDi", 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" }, { - title: "Injected completed Todo", - order: null, - completed: true, + statusCode: 201, + headers: { + "content-type": "application/json", + "x-example": "response", + "set-cookie": "mock-example=ready; Path=/", + }, }, - ], - { - statusCode: 200, - fetchResponse: true, // default - }, - ); - - await browser.url( - "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", - ); - - await browser.$("#todo-list li").waitForExist(); - - const todoElements = await browser.$$("#todo-list li"); - console.log(await Promise.all(todoElements.map(el => el.getText()))); - // will output: "[ 'Injected (non) completed Todo', 'Injected completed Todo' ]" -}); - -it("should demonstrate response overwrite with dynamic data", async ({ browser }) => { - const mock = await browser.mock("https://todo-backend-express-knex.herokuapp.com/"); - - mock.respond( - request => { - if (request.body.username === "test") { - return { ...request.body, foo: "bar" }; - } - return request.body; - }, - { - statusCode: () => 200, - headers: () => ({ foo: "bar" }), - fetchResponse: false, // do not fetch the actual response - }, - ); + ); + for (let i = 0; i < 2; i++) { + const result = await browser.execute(async () => { + const response = await fetch("/api/items", { cache: "no-store" }); + return { + status: response.status, + header: response.headers.get("x-example"), + body: await response.json(), + }; + }); + assert.deepEqual(result, { + status: 201, + header: "response", + body: { source: "mocked" }, + }); + } + const [cookie] = await browser.getCookies("mock-example"); + assert.equal(cookie?.value, "ready"); + } finally { + try { + await mock.restore(); + } finally { + await browser.deleteCookies("mock-example"); + } + } }); ``` -## Related Commands {/* #related */} - -- [respondOnce](../respondOnce) +## Related commands {/* #related */} -## References +- [respondOnce](./respondOnce.mdx) +- [redirect](./redirect.mdx) +- [browser.mock](../browser/mock.mdx) +- [Network interception](../../guides/how-to-intercept-requests-and-responses.mdx) -We'd like to give credit to the original WebdriverIO docs [article](https://webdriver.io/docs/api/mock/respond), from which we drew some information while writing our version. +## References {/* #references */} -[how-to-intercept-requests-and-responses]: ../../../guides/how-to-intercept-requests-and-responses +This page draws on the [original WebdriverIO article](https://webdriver.io/docs/api/mock/respond). diff --git a/docs/commands/mock/respondOnce.mdx b/docs/commands/mock/respondOnce.mdx index 1bbddbba..5ee8520b 100644 --- a/docs/commands/mock/respondOnce.mdx +++ b/docs/commands/mock/respondOnce.mdx @@ -1,112 +1,58 @@ -import Admonition from "@theme/Admonition"; - # respondOnce ## Overview {/* #overview */} -Use the `respondOnce` command to respond once with the specified overwrite. - -You can call `respondOnce` multiple times in succession. The responses will be used in the same order the `respondOnce` commands were called. - -If you use only `respondOnce` and access the resource more times than `respondOnce` was called, then after exhausting the fake data, the request will start returning the original response from the resource. - - - Also read the recipe "[How to Track and Intercept Network Requests and - Responses][how-to-intercept-requests-and-responses]". - +Overrides one response. Repeated calls queue responses in call order. Once the one-shot queue is exhausted, subsequent requests receive original server responses. ## Usage {/* #usage */} -```javascript -mock.respondOnce(overwrites, { header, statusCode, fetchResponse }); -``` +`mock.respondOnce(overwrites, params)` -## Command Parameters {/* #parameters */} +## Command parameters {/* #parameters */} - - - - - - - - - +Parameters and BiDi versus Classic/CDP differences match [respond](./respond.mdx#parameters), including `headers`, not `header`. In BiDi, use a nonempty string or JSON to replace the body; an empty string leaves the original body intact. As with `respond`, body callbacks and `fetchResponse: false` are not supported. The request reaches the server. - -
**Name****Type****Description**
overwritesMockOverwrite_Payload_ to overwrite the response.
headerObjectOverwrite specific headers.
statusCodeNumberOverwrite the response status code.
fetchResponseBooleanFetch the actual response before replying with fake data.
+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. -## Usage Examples {/* #examples */} +BiDi synchronously returns the same mock; Classic/CDP has no useful return value. -```javascript -async function getToDos(browser) { - await browser.$("#todo-list li").waitForExist(); +## Example {/* #examples */} - const todoElements = await browser.$$("#todo-list li"); +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. - return Promise.all(todoElements.map(el => el.getText())); -} +```javascript testplane=related-respond-once +const assert = require("node:assert/strict"); -it("should demonstrate the respondOnce command", async ({ browser }) => { - const mock = await browser.mock("https://todo-backend-express-knex.herokuapp.com/", { - method: "get", +it("mock.respondOnce: consume BiDi responses in order", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], }); - - mock.respondOnce([ - { - title: "3", - }, - { - title: "2", - }, - { - title: "1", - }, - ]); - - mock.respondOnce([ - { - title: "2", - }, - { - title: "1", - }, - ]); - - mock.respondOnce([ - { - title: "1", - }, - ]); - - await browser.url( - "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", - ); - console.log(await getToDos(browser)); // outputs: [ '3', '2', '1' ] - - await browser.url( - "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", - ); - console.log(await getToDos(browser)); // outputs: [ '2', '1' ] - - await browser.url( - "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", - ); - console.log(await getToDos(browser)); // outputs: [ '1' ] - - await browser.url( - "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", - ); - console.log(await getToDos(browser)); // outputs: the actual resource response + 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(); + } }); ``` -## Related Commands {/* #related */} - -- [respond](../respond) +## Related commands {/* #related */} -## References +- [respond](./respond.mdx) +- [reset](./reset.mdx) +- [restore](./restore.mdx) +- [Network interception](../../guides/how-to-intercept-requests-and-responses.mdx) -We'd like to give credit to the original WebdriverIO docs [article](https://webdriver.io/docs/api/mock/respondOnce), from which we drew some information while writing our version. +## References {/* #references */} -[how-to-intercept-requests-and-responses]: ../../../guides/how-to-intercept-requests-and-responses +This page draws on the [original WebdriverIO article](https://webdriver.io/docs/api/mock/respondOnce). diff --git a/docs/commands/mock/restore.mdx b/docs/commands/mock/restore.mdx index ba49bde8..7184339f 100644 --- a/docs/commands/mock/restore.mdx +++ b/docs/commands/mock/restore.mdx @@ -2,31 +2,55 @@ ## Overview {/* #overview */} -Use the `restore` command to perform all actions that [mock.clear()](../clear) does, as well as remove any fake return values or implementations. +Removes this mock's network interceptor, clears its history and disables its override rules. It does not reverse effects of requests that already ran, such as cookies stored by the browser. To undo browser emulation instead, use [browser.restore](../browser/restore.mdx). -## Usage {/* #usage */} - -```javascript -mock.restore(); -``` +Await `restore()` before the next request or the end of the test. To change rules for the same URL in the same BiDi session, use [reset](./reset.mdx) on the existing mock rather than restoring it and creating another. In `@testplane/webdriverio` 9.6.2, listeners from the old mock can still see requests blocked by the new one. -## Usage Examples {/* #examples */} - -```javascript -it("should demonstrate the addValue command", async ({ browser }) => { - const mock = await browser.mock("**/googlelogo_color_272x92dp.png"); - mock.respond("https://webdriver.io/img/webdriverio.png"); +## Usage {/* #usage */} - await browser.url("https://google.com"); // will show WebdriverIO logo instead of Google logo - mock.restore(); - await browser.url("https://google.com"); // will show the native Google logo +`await mock.restore()` + +## Parameters and result {/* #parameters */} + +Takes no arguments. Returns a Promise resolving to the same mock in BiDi and no useful value in Classic/CDP. Use it for cleanup in `finally`, including when an assertion fails. + +## Example {/* #examples */} + +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. + +```javascript testplane=related-restore +const assert = require("node:assert/strict"); + +it("mock.restore: remove interception before the next request", 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" }); + const body = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(body.source, "mocked"); + } finally { + await mock.restore(); + } + const body = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(body.source, "original"); + assert.equal(mock.calls.length, 0); + assert.throws(() => mock.respond({ source: "unused" }), /restored mock/); }); ``` -## Related Commands {/* #related */} +## Related commands {/* #related */} -- [clear](../clear) +- [clear](./clear.mdx) +- [reset](./reset.mdx) +- [browser.mock](../browser/mock.mdx) -## References +## References {/* #references */} -We'd like to give credit to the original WebdriverIO docs [article](https://webdriver.io/docs/api/mock/restore), from which we drew some information while writing our version. +This page draws on the [original WebdriverIO article](https://webdriver.io/docs/api/mock/restore). diff --git a/docs/commands/mock/waitForResponse.mdx b/docs/commands/mock/waitForResponse.mdx new file mode 100644 index 00000000..7b93b16f --- /dev/null +++ b/docs/commands/mock/waitForResponse.mdx @@ -0,0 +1,71 @@ +# waitForResponse + +## Overview {/* #overview */} + +Wait until `mock.calls` contains at least one matching entry. If you need to check a response body or a change on the page, assert it separately. + +## Usage {/* #usage */} + +`mock.waitForResponse({ timeout, interval, timeoutMsg })` + +## Parameters {/* #parameters */} + +| **Parameter** | **Type** | **Default** | **Description** | +| ------------- | -------- | ----------------------- | ----------------------------------- | +| `timeout` | `number` | `waitTimeout` (3000 ms) | Maximum wait in milliseconds. | +| `interval` | `number` | `waitInterval` (500 ms) | Polling interval in milliseconds. | +| `timeoutMsg` | `string` | — | Custom error message for a timeout. | + +## Result {/* #result */} + +`Promise` resolving to `true` once `calls` is nonempty. Rejects on timeout or a polling error. It does not return the response: inspect `mock.calls` separately. + +## Limitations {/* #limitations */} + +An old entry satisfies the wait immediately. Call [clear](./clear.mdx) **before** triggering the request you want to observe. + +- **BiDi:** the entry is recorded on `network.responseStarted`, before the body has necessarily been read. +- **Classic/CDP:** a request intercepted with `abort` or `respond(..., { fetchResponse: false })` can be recorded before it ever reaches the server. A successful wait is not evidence that the server replied. + +In `@testplane/webdriverio` 9.6.2, automatic event subscription can be skipped when a worker starts its next BiDi session. Subscribe to the two network events in each session as shown below. + +## Example {/* #examples */} + +The [local example site](../overview.mdx#run-examples) serves HTML at `/` and a successful response at `/api/items`. The second fetch starts in the page without blocking the test: the example waits for the mock entry and then for the page to finish reading the body. + +```javascript testplane=mock-wait-for-response +const assert = require("node:assert/strict"); + +it("mock.waitForResponse: wait for a new recorded response", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + await browser.execute(async () => (await fetch("/api/items")).text()); + await mock.waitForResponse({ timeout: 3000 }); + mock.clear(); + assert.equal(mock.calls.length, 0); + await browser.execute(() => { + window.requestFinished = false; + fetch("/api/items", { cache: "no-store" }) + .then(response => response.text()) + .then(() => { + window.requestFinished = true; + }); + }); + assert.equal(await mock.waitForResponse({ timeout: 3000, interval: 50 }), true); + assert.equal(mock.calls.length, 1); + await browser.waitUntil(() => browser.execute(() => window.requestFinished)); + } finally { + await mock.restore(); + } +}); +``` + +## See also {/* #see-also */} + +- [browser.mock](../browser/mock.mdx) +- [clear](./clear.mdx) +- [restore](./restore.mdx) diff --git a/docs/commands/overview.mdx b/docs/commands/overview.mdx index f62dcea4..9609a830 100644 --- a/docs/commands/overview.mdx +++ b/docs/commands/overview.mdx @@ -2,48 +2,48 @@ sidebar_class_name: hidden --- -import Admonition from "@theme/Admonition"; - # Testplane Commands -## Overview +## Overview {/* #overview */} - - Only commands for the latest version Testplane v8 and WebDriverIO v9 are described. Commands for - older versions should be referenced in the WebDriverIO documentation (example for [WebDriverIO - v8][webdriverio@8-api]). - +This reference covers Testplane v9 and its `@testplane/webdriverio` dependency. Check the protocol on the command page: WebDriver BiDi and Classic can expose different methods, even in the same browser. For older versions, use the documentation archive and [WebdriverIO v8](https://v8.webdriver.io/docs/api). -Since Testplane is based on [WebDriverIO v9][webdriverio-api], all commands provided by WebDriverIO are available in it. +Testplane does not provide the WDIO runner's implicit global `browser`, `$` and `$$`. Get `browser` from the test argument, or use `this.browser` in a regular function. An arrow function does not receive the test's `this` context. Find elements with `browser.$` and `browser.$$`. -However, the command descriptions on the [WebDriverIO][webdriverio-api] website for version 8 are not quite suitable _as is_ for Testplane users due to a number of reasons: +## Example {/* #examples */} -- In WebDriverIO, the `browser` object exists in the global scope, whereas in Testplane you need to either write `this.browser`: +Both tests open `/` relative to `baseUrl`. The test page must contain an `h1` with the text `Command examples`. -```javascript -it("should test something", async function () { - await this.browser.url("https://testplane.io"); - // test code... -}); -``` +```javascript testplane=related-overview +const assert = require("node:assert/strict"); -or get the `browser` object from the function argument (note that the `browser` object is passed inside an object!): +it("commands: use the browser fixture", async ({ browser }) => { + await browser.url("/"); + assert.equal(await browser.$("h1").getText(), "Command examples"); +}); -```javascript -it("should test something", async ({ browser }) => { - await browser.url("https://testplane.io"); - // test code... +it("commands: use this.browser with a regular function", async function () { + await this.browser.url("/"); + assert.equal(await this.browser.$("h1").getText(), "Command examples"); }); ``` -- Similarly, the `browser.$` and `browser.$$` functions in WebDriverIO are available in tests under the names `$` and `$$`, while in Testplane you need to refer to them by their full path: `browser.$` and `browser.$$`; +## Run the examples {/* #run-examples */} + +Save the JavaScript block in a Testplane test file. For examples that open relative URLs, set `baseUrl` to a local HTTP site. Serve an HTML page at `/` and provide the routes and responses listed on the command page. Run the test with `npx testplane`. The [downloadFile](./browser/downloadFile.mdx) example also needs a Selenium Grid with managed downloads. -- There are no links established between similar commands: no clustering of commands; +## Choose a command {/* #command-groups */} -Nevertheless, our description does not yet include protocol-specific commands. You can find the relevant commands on the WebDriverIO website under the "[Protocols][webdriverio-protocols]" section. +| Task | Commands | +| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Page setup and emulation | [addInitScript](./browser/addInitScript.mdx), [emulate](./browser/emulate.mdx), [restore](./browser/restore.mdx), [setViewport](./browser/setViewport.mdx) | +| Custom selectors | [addLocatorStrategy](./browser/addLocatorStrategy.mdx), [browser.custom$](./browser/customDollar.mdx), [browser.custom$$](./browser/customDollarDollar.mdx), [element.custom$](./element/customDollar.mdx), [element.custom$$](./element/customDollarDollar.mdx) | +| Frames and downloads | [switchFrame](./browser/switchFrame.mdx), [downloadFile](./browser/downloadFile.mdx) | +| Resource throttling | [throttleCPU](./browser/throttleCPU.mdx), [throttleNetwork](./browser/throttleNetwork.mdx) | +| Element operations | [execute](./element/execute.mdx), [executeAsync](./element/executeAsync.mdx), [getElement](./element/getElement.mdx), [isStable](./element/isStable.mdx), [waitForStable](./element/waitForStable.mdx) | +| Network interception | [mock](./browser/mock.mdx), [waitForResponse](./mock/waitForResponse.mdx), [request](./mock/request.mdx), [requestOnce](./mock/requestOnce.mdx), [redirect](./mock/redirect.mdx), [redirectOnce](./mock/redirectOnce.mdx), [reset](./mock/reset.mdx) | +| Testplane extensions | [extendOptions](./browser/extendOptions.mdx), [browser.unstable_captureDomSnapshot](./browser/unstable_captureDomSnapshot.mdx), [element.unstable_captureDomSnapshot](./element/unstable_captureDomSnapshot.mdx), [unstable_getCdp](./browser/unstable_getCdp.mdx) | -Also, in the descriptions of some commands, links to individual recipes are still not localized and lead to the WebDriverIO website. +## Reference scope {/* #scope */} -[webdriverio@8-api]: https://v8.webdriver.io/docs/api -[webdriverio-api]: https://webdriver.io/docs/api -[webdriverio-protocols]: https://webdriver.io/docs/api/webdriver +Low-level WebDriver, BiDi and Appium commands are not duplicated here: see [WebdriverIO protocols](https://webdriver.io/docs/api/webdriver). Methods of `InitScript` and clock objects are documented with [addInitScript](./browser/addInitScript.mdx) and [emulate](./browser/emulate.mdx), not as separate browser commands. When using external recipes, account for version differences and how Testplane provides `browser`. diff --git a/docs/guides/how-to-intercept-requests-and-responses.mdx b/docs/guides/how-to-intercept-requests-and-responses.mdx index 17bfb1b5..6d6258fc 100644 --- a/docs/guides/how-to-intercept-requests-and-responses.mdx +++ b/docs/guides/how-to-intercept-requests-and-responses.mdx @@ -7,15 +7,11 @@ import Admonition from "@theme/Admonition"; [//]: # "TODO: add screencasts" -This recipe only works when using _Chrome DevTools Protocol (CDP)_. - -Read details in the section “[How to Use CDP in Testplane][how-to-use-cdp]” +These examples use [Chrome DevTools Protocol (CDP)][how-to-use-cdp]. The `browser.mock` examples assume a **Classic** WebDriver session with a CDP connection. In a BiDi session, [browser.mock](../commands/browser/mock.mdx) uses BiDi network events instead: for example, `respond(..., { fetchResponse: false })` does not prevent the request from reaching the server. -CDP has [Fetch][fetch] and [Network][network] domains that provide full access to all network requests and responses. If we used the Webdriver protocol, we would have to write a separate proxy server and route all traffic through it. - -In _webdriverio_, there is a [mock][mock] method for working with network requests, which uses the API of the [Fetch][fetch] domain. +In Classic, `browser.mock` intercepts traffic through CDP's [Fetch][fetch] domain. The [Network][network] domain exposes additional network events. With this method, we can: diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/basic-guides/selectors.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/basic-guides/selectors.mdx index c304b807..285badbb 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/basic-guides/selectors.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/basic-guides/selectors.mdx @@ -313,6 +313,10 @@ const slotElements = await customElement.shadow$$(".slot-item"); - нужен доступ к элементам внутри shadow root - работаете с дизайн-системой на базе Web Components +## Собственные стратегии поиска {/* #custom-locator-strategies */} + +Если стандартного селектора недостаточно, зарегистрируйте стратегию через [browser.addLocatorStrategy](../commands/browser/addLocatorStrategy.mdx). Используйте [browser.custom$](../commands/browser/customDollar.mdx) для одного элемента и [browser.custom$$](../commands/browser/customDollarDollar.mdx) для нескольких. Для поиска внутри конкретного элемента доступны [element.custom$](../commands/element/customDollar.mdx) и [element.custom$$](../commands/element/customDollarDollar.mdx). Функция стратегии выполняется в браузере, поэтому передавайте ей данные аргументами, а не через замыкания Node.js. Проверенные примеры приведены на страницах команд. + ## Testing Library Testing Library позволяет искать элементы так, как их ищут на странице пользователи — по тексту, типу элемента или другим атрибутам, которые не зависят от деталей вашей верстки. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/basic-guides/user-environment-emulation.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/basic-guides/user-environment-emulation.mdx index e356eaaf..97a9910e 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/basic-guides/user-environment-emulation.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/basic-guides/user-environment-emulation.mdx @@ -327,60 +327,71 @@ it("применяет стили для темной цветовой схем }); ``` -## Сеть +## Сеть {/* #network */} -### Отсутствие сети + -Для проверки работы приложения без сети используйте [`browser.throttleNetwork("offline")`][throttle-network]. +### Отсутствие сети {/* #offline-mode */} -Например, так можно проверить сообщение об ошибке при сетевом запросе: + -```typescript -it("показывает сообщение при отсутствии сети", async ({ browser }) => { - await browser.url("/"); +Для реального отключения запросов используйте [throttleNetwork][throttle-network]. Нужен Chromium с доступным CDP/Puppeteer, одна вкладка, `isolation: false` и `testsPerSession: 1`: реализация выбирает первую страницу Puppeteer. Сначала откройте страницу, затем отключите сеть. - await browser.throttleNetwork("offline"); +В проверенной связке Testplane 9.3.2 / WDIO 9.6.2 / Chrome 150 вызов с профилем `online` не восстановил сеть после `offline`. Поэтому пример заканчивает офлайн-сессию и проверяет соединение в новой, а не обещает восстановление тем же вызовом. `baseUrl` должен указывать на тестовый HTTP-сервер, отвечающий `200` на корневой путь. - const loadOrders = await browser.getByTestId("load-orders"); - await loadOrders.click(); +```javascript testplane=browser-throttle-network +const assert = require("node:assert/strict"); - const networkError = await browser.findByTestId("network-error"); - await expect(networkError).toHaveText("Нет подключения к сети"); +// 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); +}); - 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); }); ``` -Сначала загрузите страницу, а затем отключите сеть перед действием, которое отправляет запрос. В отличие от `emulate()`, `throttleNetwork()` нужно вызывать после навигации. Чтобы вернуть обычный сетевой режим, используйте профиль `"online"`. +### Медленное соединение {/* #slow-connection */} -### Медленное соединение + -Для проверки интерфейса при медленном соединении передайте параметры сети в [`browser.throttleNetwork()`][throttle-network]: +Для ограничения скорости передайте объект в [throttleNetwork][throttle-network]. Пример использует те же условия изоляции. Сервер по адресу `baseUrl` должен отдавать HTML на `/` и JSON с `source: "original"` на `/api/items`. -```typescript -it("показывает состояние загрузки при медленной сети", 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"); }); ``` -Объект содержит четыре поля: `offline`, задержку `latency` в миллисекундах, а также скорости загрузки и отправки данных `downloadThroughput` и `uploadThroughput` в байтах в секунду. - -Для типовых условий параметры можно не задавать вручную. Вместо объекта передайте имя готового профиля, например `"Good3G"` или `"offline"`. +`offline` включает офлайн-режим, `latency` задает задержку в миллисекундах, `downloadThroughput` и `uploadThroughput` — скорость в байтах в секунду. Вместо объекта можно передать профиль, например `Good3G`. Ограниченная сессия не переиспользуется в следующем тесте. ### navigator.onLine @@ -400,21 +411,28 @@ it("показывает офлайн-режим", async ({ browser }) => { `browser.emulate("onLine", false)` только меняет значение `navigator.onLine`, но не отключает сеть: HTTP-запросы продолжают выполняться. -## Производительность CPU - -Для проверки интерфейса при ограниченной производительности процессора используйте [`browser.throttleCPU()`][throttle-cpu]. +## Производительность CPU {/* #cpu-performance */} -Например, так можно проверить сценарий при четырехкратном замедлении CPU: + -```typescript -it("работает при замедленном CPU", async ({ browser }) => { - await browser.throttleCPU(4); +[throttleCPU][throttle-cpu] замедляет выполнение кода в Chromium через CDP/Puppeteer. Как и для сети, нужны одна вкладка и `isolation: false`: команда работает с первой страницей Puppeteer. Откройте страницу до вызова команды. В `baseUrl` укажите адрес тестовой HTML-страницы. - await browser.url("/"); +Пример задает двукратное замедление и отменяет его в `finally`. - // ... +```javascript testplane=browser-throttle-cpu +const assert = require("node:assert/strict"); - await browser.throttleCPU(1); +it("throttleCPU: run a page with a slower CPU", async ({ browser }) => { + await browser.url("/"); + try { + await browser.throttleCPU(2); + await browser.execute(() => { + document.body.innerHTML = ""; + }); + assert.equal(await browser.$("button").getText(), "Ready"); + } finally { + await browser.throttleCPU(1); + } }); ``` @@ -551,26 +569,26 @@ describe("темная цветовая схема", () => { Если настройка должна действовать всю сессию, создайте для нее отдельную конфигурацию браузера. Так удобнее задавать язык браузера, запускать тесты с отключенным JavaScript и фиксировать размер окна с помощью [`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 diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/addInitScript.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/addInitScript.mdx new file mode 100644 index 00000000..38ffc0c4 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/addInitScript.mdx @@ -0,0 +1,58 @@ +# addInitScript + +## Обзор {/* #overview */} + +Выполните функцию в новых документах текущей вкладки или окна до запуска скриптов страницы. Это позволяет подготовить значения до того, как приложение их прочитает. Функция также выполняется в дочерних фреймах этого верхнеуровневого контекста при их добавлении или переходе на другую страницу. + +Скрипт регистрируется для вкладки или окна, текущих в момент вызова `addInitScript`. Он не распространяется автоматически на другие вкладки и окна, в том числе открытые позже. Чтобы использовать его там, переключитесь на нужную вкладку или окно и зарегистрируйте скрипт отдельно до перехода на страницу. + +## Использование {/* #usage */} + +`browser.addInitScript(script, ...args)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------ | ----------- | ---------------- | -------------------------------------------------------------------- | +| `script` | `Function` | Обязателен | Функция для выполнения в браузере, без доступа к переменным Node.js. | +| `args` | `unknown[]` | [] | Аргументы, сериализуемые в JSON и передаваемые функции. | + +## Результат {/* #result */} + +`Promise`. Чтобы получить данные в Node.js, до навигации подпишитесь через `script.on("data", listener)`. Браузерная функция отправляет данные через свой последний аргумент `emit`. Подписка синхронная, а `script.remove()` возвращает промис. + +## Ограничения {/* #limitations */} + +Нужна сессия WebDriver BiDi (`webSocketUrl: true`). Зарегистрируйте функцию до навигации. После `await script.remove()` она не запустится в новых документах, но уже загруженная страница не изменится. + +В `@testplane/webdriverio` 9.6.2 передавайте функцию, а не строку. В ее теле используйте обычные кавычки: шаблонные строки могут нарушить синтаксис внедряемого скрипта. Символы вне Latin-1 (например, кириллица) в коде функции или сериализованных аргументах могут помешать регистрации. + +## Пример {/* #examples */} + +На [тестовом сайте](../overview.mdx#run-examples) страница `/navigation` при загрузке выполняет `window.initialSeed = window.navigationSeed ?? null`. Тест проверяет, какое значение прочитал **скрипт страницы** до и после удаления инициализатора. + +```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 */} + +- [execute](./execute.mdx) +- [url](./url.mdx) +- [emulate](./emulate.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/addLocatorStrategy.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/addLocatorStrategy.mdx new file mode 100644 index 00000000..464385c3 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/addLocatorStrategy.mdx @@ -0,0 +1,48 @@ +# addLocatorStrategy + +## Обзор {/* #overview */} + +Зарегистрируйте переиспользуемый способ поиска элементов. Затем вызывайте стратегию через `custom$` или `custom$$` у браузера или элемента. + +## Использование {/* #usage */} + +`browser.addLocatorStrategy(name, strategy)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------ | ---------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `name` | `string` | Обязателен | Уникальное имя стратегии в объекте браузера. | +| `strategy` | `Function` | Обязателен | Браузерная функция, возвращающая DOM-элемент или массив DOM-элементов. Перед возвратом преобразуйте NodeList через Array.from. | + +## Результат {/* #result */} + +`void`. Регистрация синхронная и сама по себе не выполняет поиск. + +## Ограничения {/* #limitations */} + +Зарегистрируйте стратегию до первого использования. Повторная регистрация имени вызывает ошибку. Callback выполняется в браузере и не может читать замыкания Node.js. Для общего использования зарегистрируйте стратегию в `prepareBrowser`. + +## Пример {/* #examples */} + +Настройте `baseUrl` на свой локальный тестовый HTTP-сайт, где `/` возвращает HTML-страницу. Пример выполняется внутри обычного файла тестов Testplane. + +```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 = ''; + }); + browser.addLocatorStrategy("byTest", value => document.querySelector(`[data-test="${value}"]`)); + const button = await browser.custom$("byTest", "save"); + assert.equal(await button.getText(), "Save"); +}); +``` + +## См. также {/* #see-also */} + +- [custom$](./customDollar.mdx) +- [custom$$](./customDollarDollar.mdx) +- [prepareBrowser](../../reference/config/prepare-browser.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/customDollar.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/customDollar.mdx new file mode 100644 index 00000000..cb17c60f --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/customDollar.mdx @@ -0,0 +1,48 @@ +# custom$ + +## Обзор {/* #overview */} + +Найдите один элемент с помощью стратегии, зарегистрированной через `addLocatorStrategy`. Способ выбора элемента определяет сама стратегия. + +## Использование {/* #usage */} + +`browser.custom$(strategyName, ...strategyArguments)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------------- | ----------- | ---------------- | --------------------------------------- | +| `strategyName` | `string` | Обязателен | Имя зарегистрированной стратегии. | +| `strategyArguments` | `unknown[]` | [] | Аргументы браузерной функции стратегии. | + +## Результат {/* #result */} + +Ожидаемая ссылка на элемент, разрешающаяся в `WebdriverIO.Element`. Если стратегия вернула несколько элементов, используется первый. + +## Ограничения {/* #limitations */} + +Неизвестное имя стратегии вызывает ошибку. Найденный элемент не обязательно видим или доступен для нажатия: используйте соответствующие ожидания или проверки. Если стратегия ничего не нашла, последующие команды элемента могут завершиться ошибкой. + +## Пример {/* #examples */} + +Настройте `baseUrl` на свой локальный тестовый HTTP-сайт, где `/` возвращает HTML-страницу. Пример выполняется внутри обычного файла тестов Testplane. + +```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 = ''; + }); + browser.addLocatorStrategy("byTest", value => document.querySelector(`[data-test="${value}"]`)); + const button = await browser.custom$("byTest", "save"); + assert.equal(await button.getText(), "Save"); +}); +``` + +## См. также {/* #see-also */} + +- [addLocatorStrategy](./addLocatorStrategy.mdx) +- [custom$$](./customDollarDollar.mdx) +- [$](./$.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/customDollarDollar.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/customDollarDollar.mdx new file mode 100644 index 00000000..bd7e7e58 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/customDollarDollar.mdx @@ -0,0 +1,51 @@ +# custom$$ + +## Обзор {/* #overview */} + +Найдите несколько элементов с помощью зарегистрированной стратегии. Если DOM API возвращает NodeList, преобразуйте его через `Array.from` внутри стратегии. + +## Использование {/* #usage */} + +`browser.custom$$(strategyName, ...strategyArguments)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------------- | ----------- | ---------------- | --------------------------------------- | +| `strategyName` | `string` | Обязателен | Имя зарегистрированной стратегии. | +| `strategyArguments` | `unknown[]` | [] | Аргументы браузерной функции стратегии. | + +## Результат {/* #result */} + +Ожидаемая коллекция, разрешающаяся в массив объектов `WebdriverIO.Element`. Если совпадений нет, возвращается пустой массив. + +## Ограничения {/* #limitations */} + +Неизвестное имя стратегии вызывает ошибку. Команда возвращает совпадения на момент поиска и не ожидает появления заданного количества элементов. + +## Пример {/* #examples */} + +Настройте `baseUrl` на свой локальный тестовый HTTP-сайт, где `/` возвращает HTML-страницу. Пример выполняется внутри обычного файла тестов Testplane. + +```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 = "
  • First
  • Second
"; + }); + 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 */} + +- [addLocatorStrategy](./addLocatorStrategy.mdx) +- [custom$](./customDollar.mdx) +- [$$](./$$.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/downloadFile.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/downloadFile.mdx new file mode 100644 index 00000000..377f5272 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/downloadFile.mdx @@ -0,0 +1,70 @@ +# downloadFile + +## Обзор {/* #overview */} + +Копирует файл, скачанный браузером на узле Selenium Grid, в файловую систему процесса Testplane. Метод не скачивает произвольный URL. + +## Условия использования {/* #requirements */} + +Нужен Selenium Grid с включенными управляемыми загрузками (`--enable-managed-downloads true`) и capability `se:downloadsEnabled: true`. Поддерживаются Chrome, Edge и Firefox. Режим `gridUrl: "local"` сам по себе не предоставляет API загрузок Selenium. Подробнее — в [документации Selenium](https://www.selenium.dev/documentation/webdriver/drivers/remote_webdriver/#enable-downloads-in-the-grid). + +## Использование {/* #usage */} + +`browser.downloadFile(fileName, targetDirectory)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **Описание** | +| ----------------- | -------- | ------------------------------------------------------ | +| `fileName` | `string` | Имя файла из `getDownloadableFiles().names`, не URL. | +| `targetDirectory` | `string` | Локальный каталог назначения; создается автоматически. | + +## Результат {/* #result */} + +`Promise<{ files: string[] }>`: абсолютные пути распакованных файлов. Метод также оставляет архив `.zip` в каталоге назначения. В этой версии ошибки распаковки записываются в лог и могут привести к пустому массиву `files`; проверяйте наличие и содержимое результата. + +## Пример {/* #examples */} + +Настройте `gridUrl` на адрес своего Grid, включите `se:downloadsEnabled: true` в `desiredCapabilities`. Укажите `baseUrl` тестового HTTP-сайта: `/` возвращает HTML, а `/report.csv` — текст `name,value\nexample,42\n` с заголовком `Content-Disposition: attachment; filename="report.csv"`. + +Запускайте пример в отдельной сессии (`testsPerSession: 1`). Адрес `baseUrl` должен быть доступен **с узла Grid**. `getDownloadableFiles()` возвращает текущий список файлов, а не ждет окончания этой загрузки. При очистке `deleteDownloadableFiles()` удаляет **все** управляемые загрузки сессии, а не только `report.csv`. + +```javascript testplane=selenium-download-file suite=selenium +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const os = require("node:os"); +const path = require("node:path"); + +it("downloadFile: copy a browser download from Selenium Grid", async ({ browser }) => { + const targetDirectory = await fs.mkdtemp(path.join(os.tmpdir(), "testplane-download-")); + try { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = 'Download report'; + }); + await browser.$("a").click(); + await browser.waitUntil( + async () => { + const { names } = await browser.getDownloadableFiles(); + return names.includes("report.csv"); + }, + { timeout: 10000, timeoutMsg: "The CSV was not downloaded on the Grid node" }, + ); + const { files } = await browser.downloadFile("report.csv", targetDirectory); + const localFile = path.join(targetDirectory, "report.csv"); + assert.ok(files.includes(localFile)); + assert.equal(await fs.readFile(localFile, "utf8"), "name,value\nexample,42\n"); + } finally { + try { + await browser.deleteDownloadableFiles(); + } finally { + await fs.rm(targetDirectory, { recursive: true, force: true }); + } + } +}); +``` + +## См. также {/* #see-also */} + +- [url](./url.mdx) +- [waitUntil](./waitUntil.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/emulate.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/emulate.mdx new file mode 100644 index 00000000..85f84a64 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/emulate.mdx @@ -0,0 +1,74 @@ +# emulate + +## Обзор {/* #overview */} + +Подмените часть браузерного окружения, например user agent или часы. Для восстановления окружения в том же тесте используйте возвращенную функцию очистки или объект часов. + +## Использование {/* #usage */} + +`browser.emulate(scope, options)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------ | ----------------- | ----------------------- | ---------------------------------------------------------------------------- | +| `scope` | `string` | Обязателен | Один из режимов: clock, geolocation, userAgent, device, colorScheme, onLine. | +| `options` | Зависит от режима | Обязателен, кроме clock | Настройки выбранного режима, описанные ниже. | + +Поддерживаемые режимы: + +- `clock` — Настройки виртуальных часов, включая `now` и `toFake`; виртуальные таймеры продвигаются через `tick`. +- `geolocation` — координаты для `navigator.geolocation.getCurrentPosition`, например `{ latitude: 52.52, longitude: 13.405 }`. Подмена не меняет `watchPosition` и разрешения браузера. +- `userAgent` — Строка для `navigator.userAgent`, а не HTTP-заголовков запросов. +- `device` — Имя поддерживаемого профиля устройства; меняет viewport, DPR и user agent, но не движок и сенсорный ввод. +- `colorScheme` — `"light"` или `"dark"`; в этой реализации влияет на `matchMedia`, но не на CSS-медиазапросы. +- `onLine` — Булево значение для `navigator.onLine`; не блокирует сетевые запросы. + +## Результат {/* #result */} + +Для `clock` — `Promise`, для остальных режимов — промис с асинхронной функцией восстановления. Объект часов предоставляет методы `tick(milliseconds)`, `setSystemTime(dateOrTimestamp)`, `restore()` и `install(options)`. + +## Ограничения {/* #limitations */} + +Нужен WebDriver BiDi (`webSocketUrl: true`). Включайте эмуляцию до навигации: большинство подмен действует с загрузки нового документа. Часы меняются и в уже открытом документе. Для каждой подмены выберите один [способ очистки](./restore.mdx#limitations). + +В `@testplane/webdriverio` 9.6.2 `clock.restore()` возвращает обычные таймеры в текущем документе, но скрипт установки часов остается зарегистрированным для следующих загрузок. Если следующий тест должен начаться в чистой сессии, задайте `testsPerSession: 1` для тестов с подменой часов. + +## Пример {/* #examples */} + +Настройте `baseUrl` на свой локальный тестовый HTTP-сайт, где `/` возвращает HTML-страницу. Пример выполняется внутри обычного файла тестов Testplane. + +```javascript testplane=browser-emulate +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(); + } +}); +``` + +## См. также {/* #see-also */} + +- [restore](./restore.mdx) +- [setViewport](./setViewport.mdx) +- [Эмуляция окружения](../../basic-guides/user-environment-emulation.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/executeAsync.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/executeAsync.mdx index 74d58b14..de02bbca 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/executeAsync.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/executeAsync.mdx @@ -2,58 +2,47 @@ ## Обзор {/* #overview */} -Используйте команду `executeAsync`, чтобы выполнить _асинхронно_ указанный JavaScript-код на странице текущего выбранного фрейма. +Выполняет JavaScript в текущем фрейме и возвращает значение, переданное в callback. Команда устарела: для нового кода используйте [execute](./execute.mdx) с асинхронной функцией. -Последним аргументом команды должен быть колбэк, который будет вызван, как только скрипт завершит свою работу. В качестве входного параметра команда передает в колбэк результат выполнения скрипта. - -Аргумент `script` определяет сценарий для выполнения в виде тела функции. Функция будет вызвана с предоставленным массивом `args`, и доступ к значениям может быть получен через объект `arguments` в указанном порядке. Последним аргументом всегда должна быть колбэк-функция, которая будет вызвана после того, как скрипт будет выполнен. - -Аргументами могут быть любые JSON-примитивы, массивы или объекты JSON. Объекты JSON, которые определяют ссылку на _WebElement,_ будут преобразованы в соответствующий элемент DOM. Аналогично, любые _WebElements_ в результате скрипта будут возвращены клиенту в виде объектов _WebElement JSON_. +Callback добавляет сама команда как последний аргумент **браузерной функции**. Его не нужно передавать отдельным аргументом `browser.executeAsync`. Вызовите callback, чтобы завершить команду. ## Использование {/* #usage */} -```javascript -await browser.executeAsync(script, arguments); -``` +`await browser.executeAsync(script, ...args)` ## Параметры команды {/* #parameters */} - - - - - - - +- `script` — функция или строка с телом функции. Код выполняется в браузере, без Node.js API и локальных замыканий. +- `args` — сериализуемые аргументы, передаваемые перед callback; ссылки WebElement преобразуются в DOM-элементы. + +Результат — Promise со значением, переданным в callback. В Classic настройте тайм-аут `script` через [setTimeout](./setTimeout.mdx). В BiDi-реализации нет отдельного таймера ожидания callback; всегда вызывайте его и ограничивайте тест через `testTimeout`. - -
**Имя****Тип****Описание**
scriptString или FunctionСкрипт, который необходимо выполнить.
argumentsAnyАргументы для скрипта. Последним аргументом должна быть колбэк-функция, которая будет вызвана после того, как скрипт будет выполнен.
+## Пример {/* #examples */} -## Примеры использования {/* #examples */} +Укажите в `baseUrl` адрес тестовой HTML-страницы. -```javascript -it("should execute async JavaScript on the page", async ({ browser }) => { - await browser.setTimeout({ script: 5000 }); +```javascript testplane=related-execute-async +const assert = require("node:assert/strict"); +it("browser.executeAsync: return a result through the injected callback", async ({ browser }) => { + await browser.url("/"); const result = await browser.executeAsync( - function (a, b, c, d, done) { - // здесь мы в browser-контексте: доступа к консоли и к клиенту у нас нет - setTimeout(() => { - done(a + b + c + d); - }, 3000); + (a, b, done) => { + setTimeout(() => done(a + b), 20); }, - 1, - 2, - 3, 4, + 6, ); - - // здесь мы в node.js-контексте: доступ к консоли и к клиенту у нас есть - console.log(result); // выведет: 10 + assert.equal(result, 10); }); ``` ## Связанные команды {/* #related */} -- [execute](../execute) -- [setTimeout](../setTimeout) +- [execute](./execute.mdx) +- [element.executeAsync](../element/executeAsync.mdx) +- [setTimeout](./setTimeout.mdx) + +## Источники {/* #references */} + +Материал учитывает [исходную статью WebdriverIO](https://webdriver.io/docs/api/browser/executeAsync). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/extendOptions.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/extendOptions.mdx new file mode 100644 index 00000000..b0693da2 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/extendOptions.mdx @@ -0,0 +1,62 @@ +# extendOptions + +## Обзор {/* #overview */} + +Поверхностно обновляет настройки текущего объекта браузера WebdriverIO. Используйте метод для клиентских параметров, например интервалов ожидания, а не для изменения конфигурации раннера Testplane или capabilities сессии. + +## Использование {/* #usage */} + +`browser.extendOptions(options)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------ | ------------------------- | ---------------- | ---------------------------------------------------- | +| `options` | `Record` | Обязательный | Поля верхнего уровня для записи в `browser.options`. | + +## Результат {/* #result */} + +`Promise`: команда завершается без возвращаемого значения. + +## Ограничения {/* #limitations */} + +Вложенные объекты заменяются, а не объединяются рекурсивно. Поля, которых нет в аргументе, сохраняются. Метод не проверяет имена параметров и не пересоздает сессию: изменение действует только там, где команда читает этот runtime-параметр. Конфигурация, возвращаемая `getConfig()`, не меняется. Сохраните изменяемые значения и восстановите их в `finally`. + +## Пример {/* #examples */} + +Настройте `baseUrl` на локальный HTTP-сайт, где `/` возвращает HTML-страницу. Запустите пример в файле тестов Testplane. + +```javascript testplane=testplane-browser-extend-options +const assert = require("node:assert/strict"); + +it("extendOptions: change WebdriverIO wait settings for this browser", async ({ browser }) => { + const original = { + waitforTimeout: browser.options.waitforTimeout, + waitforInterval: browser.options.waitforInterval, + }; + const configuredTimeout = (await browser.getConfig()).waitTimeout; + assert.equal(typeof configuredTimeout, "number"); + try { + const result = await browser.extendOptions({ waitforTimeout: 1000, waitforInterval: 50 }); + assert.equal(result, undefined); + assert.equal(browser.options.waitforTimeout, 1000); + assert.equal(browser.options.waitforInterval, 50); + assert.equal((await browser.getConfig()).waitTimeout, configuredTimeout); + await browser.url("/"); + await browser.execute(() => { + setTimeout(() => { + document.body.innerHTML = '

Ready

'; + }, 100); + }); + await browser.$("#ready").waitForExist(); + assert.equal(await browser.$("#ready").getText(), "Ready"); + } finally { + await browser.extendOptions(original); + } +}); +``` + +## См. также {/* #see-also */} + +- [getConfig](./getConfig.mdx) +- [waitUntil](./waitUntil.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/getState.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/getState.mdx index 80faac68..8d7c1734 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/getState.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/getState.mdx @@ -6,53 +6,55 @@ import Version from "../../_partials/specs/version.mdx"; ## Обзор {/* #overview */} -Эта команда возвращает состояние страницы из файла, ранее сохраненного с помощью команды [saveState][saveState]. +Читает JSON-файл состояния, созданный [saveState](./saveState.mdx), и возвращает его содержимое. Команда **не восстанавливает состояние браузера**: не меняет cookies, хранилища и текущую страницу. Для восстановления используйте [restoreState](./restoreState.mdx). ## Использование {/* #usage */} -```typescript -import type { SaveStateData } from "testplane"; - -const stateDump: SaveStateData = await browser.getState({ - path: "./stateDump.json", -}); -``` +`await browser.getState(options)` ## Параметры команды {/* #parameters */} - - - - - - - - - - - - - - - - - -
**Имя****Тип****Значение по умолчанию****Описание**
path`string``-`Путь к файлу с состоянием.
- -## Usage Examples {/* #examples */} - -Save state in file. - -```typescript -it("test", async ({ browser }) => { - const stateData = await browser.getState({ - path: "./stateDump.json", - }); +| Параметр | Тип | Описание | +| -------------- | -------- | ------------------------------------------------------------------------------------------ | +| `options.path` | `string` | Путь к JSON-файлу. Относительный путь разрешается от рабочего каталога процесса Testplane. | + +Если аргумент `options` пропущен, используются `browser.config.stateOpts`. Явно переданный объект не объединяется с настройками: `getState({})` не подставит путь из конфигурации. + +## Результат и ошибки {/* #result */} + +Возвращает Promise с прочитанными данными. Для файла `saveState` это `SaveStateData`: необязательный массив `cookies` и `framesData`, где состояния `localStorage` и `sessionStorage` сгруппированы по origin. Схема прочитанного JSON не проверяется. + +Если путь не задан, команда пишет ошибку в лог и возвращает `null`. Ошибки чтения или разбора JSON отклоняют промис. В файле состояния могут быть cookies сессии и значения из хранилищ: не коммитьте его и не выводите содержимое в лог теста. + +## Пример {/* #examples */} + +Укажите в `baseUrl` адрес тестовой HTML-страницы. Пример сохраняет localStorage во временный файл, меняет значение в браузере и проверяет, что чтение файла не восстанавливает сессию. + +```javascript testplane=related-get-state +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const os = require("node:os"); +const path = require("node:path"); + +it("getState: read a saved file without restoring the session", async ({ browser }) => { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), "testplane-state-")); + const statePath = path.join(directory, "state.json"); + try { + await browser.url("/"); + const origin = new URL(await browser.getUrl()).origin; + await browser.execute(() => localStorage.setItem("example", "saved")); + await browser.saveState({ path: statePath, cookies: false, localStorage: true }); + await browser.execute(() => localStorage.setItem("example", "current")); + const state = await browser.getState({ path: statePath }); + assert.equal(state.framesData[origin].localStorage.example, "saved"); + assert.equal(await browser.execute(() => localStorage.getItem("example")), "current"); + } finally { + await fs.rm(directory, { recursive: true, force: true }); + } }); ``` -## Related Commands {/* #related */} - -- [saveState][saveState] +## Связанные команды {/* #related */} -[saveState]: ../saveState +- [saveState](./saveState.mdx) +- [restoreState](./restoreState.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/mock.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/mock.mdx index 26bc37da..3b16317e 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/mock.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/mock.mdx @@ -1,135 +1,97 @@ -import Admonition from "@theme/Admonition"; - # mock ## Обзор {/* #overview */} -Используйте команду `mock`, чтобы имитировать ответ на запрос. +Создает перехватчик сетевых запросов. Возвращаемый объект позволяет наблюдать запросы, заменять ответы или прерывать загрузку. Возможности зависят от протокола сессии. -Вы можете включать имитацию в зависимости от урла, заголовков или статус-кода. Вызов метода `mock` возвращает объект-заглушку _(stub)_, который вы можете использовать, чтобы модифицировать ответ от веб-ресурса. С помощью объекта-заглушки вы можете возвращать ответ-имитацию или ронять запрос. +- **WebDriver BiDi**: перехват через сетевые события BiDi. Дополнительно доступны изменение запроса, перенаправление и сброс правил. +- **Classic с CDP/Puppeteer**: прежняя реализация для совместимого браузера. Это не универсальная возможность Classic WebDriver. +- **WebDriver-перехват Sauce Labs**: отдельное расширение провайдера с другим API и без событий; не переносите на него BiDi-пример без проверки. -Существует 3 способа модифицировать ответ: +О настройке Classic — в материалах [«Как использовать CDP»](../../guides/how-to-use-cdp.mdx) и [«Перехват запросов через CDP»](../../guides/how-to-intercept-requests-and-responses.mdx). Сравнение ниже относится к `@testplane/webdriverio` 9.6.2. Пример на этой странице использует BiDi. -- вернуть кастомный JSON-объект (например, чтобы имитировать ответ на API-запрос); -- заменить ответ локальным файлом (подсунуть модифицированный JavaScript-файл); -- перенаправить на другой URL и подсунуть полученный оттуда ответ. +## Использование {/* #usage */} - -Команда _mock_ работает только при использовании _Chrome DevTools Protocol (CDP)_. +`await browser.mock(url, filters)` -Читайте подробности в разделе «[Как использовать Chrome DevTools Protocol в testplane][how-to-use-cdp]». +## Параметры команды {/* #parameters */} -А также читайте рецепт «[Как отслеживать и перехватывать сетевые запросы и ответы][how-to-intercept-requests-and-responses]». +| Параметр | BiDi | Classic/CDP | +| ----------------- | ----------------------------------------------------------------------------------- | ----------------------------------------- | +| `url` | Строка `URLPattern`: абсолютный HTTP(S)-шаблон или pathname, например `/api/items`. | Glob-строка или `RegExp`. | +| `method` | Строка или функция-фильтр HTTP-метода. | То же. | +| `requestHeaders` | Объект или функция-фильтр заголовков запроса. | То же. | +| `responseHeaders` | Объект или функция-фильтр заголовков ответа. | Не применяется. | +| `headers` | Не используйте; для ответа есть `responseHeaders`. | Фильтр **заголовков ответа**, не запроса. | +| `postData` | Не применяется. | Строка или функция-фильтр тела запроса. | +| `statusCode` | Число или функция-фильтр статуса ответа. | То же. | - +Фильтры передаются одним объектом во втором, необязательном аргументе. В BiDi `statusCode` и `responseHeaders` фильтруют **ответы**, а не исходящие запросы: `request`, `redirect` или `abort` могут сработать раньше, чем станет известен статус. Чтобы ограничить такие правила, фильтруйте по методу или заголовкам запроса. Glob-шаблоны CDP и строки `URLPattern` BiDi не взаимозаменяемы. -## Использование {/* #usage */} +## Результат {/* #result */} -```javascript -await browser.mock(url, { method, headers, responseHeaders, postData, statusCode }); -``` +Команда возвращает Promise с объектом мока. Общие операции: [respond](../mock/respond.mdx), [respondOnce](../mock/respondOnce.mdx), [abort](../mock/abort.mdx), [abortOnce](../mock/abortOnce.mdx), [waitForResponse](../mock/waitForResponse.mdx), [clear](../mock/clear.mdx) и [restore](../mock/restore.mdx). Сигнатуры могут различаться между реализациями. -## Параметры команды {/* #parameters */} +Только в BiDi: [request](../mock/request.mdx), [requestOnce](../mock/requestOnce.mdx), [redirect](../mock/redirect.mdx), [redirectOnce](../mock/redirectOnce.mdx) и [reset](../mock/reset.mdx). - - - - - - - - - - - - - -
**Имя****Тип****Описание**
urlStringURL, запрос которого нужно имитировать.
methodString или Functionhttp-метод, по которому нужно фильтровать ресурс.
headersObject или FunctionЗаголовки запроса, по которым нужно фильтровать ресурс.
responseHeadersObject или FunctionЗаголовки ответа, по которым нужно фильтровать ресурс.
postDataString или FunctionpostData запроса, по которому нужно фильтровать ресурс.
statusCodeNumber или FunctionКод статуса, по которому нужно фильтровать ресурс.
- -## Примеры использования {/* #examples */} - -```javascript -it("should mock network resources", async ({ browser }) => { - // используем статическую строку - const userListMock = await browser.mock("**" + "/users/list"); - - // также мы можем имитировать ответы в зависимости - // от заголовков запроса или ответа, статус-кода, или postData - const strictMock = await browser.mock("**", { - // мокаем все json-ответы - statusCode: 200, - headers: { "Content-Type": "application/json" }, - responseHeaders: { "Cache-Control": "no-cache" }, - postData: "foobar", - }); +`mock.calls` хранит историю совпадений, а не только полученные ответы: - // функция-компаратор - const apiV1Mock = await browser.mock("**" + "/api/v1", { - statusCode: statusCode => statusCode >= 200 && statusCode <= 203, - headers: headers => - headers["Authorization"] && headers["Authorization"].startsWith("Bearer "), - responseHeaders: headers => headers["Impersonation"], - postData: data => typeof data === "string" && data.includes("foo"), - }); -}); +- BiDi: объекты `network.responseStarted`, например `call.request.url` и `call.response.status`. Это не гарантия полной загрузки тела. +- Classic/CDP: в записи есть `url`, `body`, `headers`, `responseHeaders` и `statusCode`. Отмененный или подмененный до отправки запрос может попасть в историю без HTTP-ответа сервера. -it("should modify API responses", async ({ browser }) => { - // фильтруем по методу - const todoMock = await browser.mock("**" + "/todos", { - method: "get", - }); +Не используйте поля одной реализации как общий контракт. `clear()` очищает историю, но сохраняет правила. `restore()` удаляет перехватчик; ожидайте его завершения в `finally`. - // имитируем ответ эндпойнта заготовленной фикстурой - mock.respond([ - { - title: "Injected Todo", - order: null, - completed: false, - url: "http://todo-backend-express-knex.herokuapp.com/916", - }, - ]); - - // отвечаем другим статус-кодом или заголовком - mock.respond( - [ - { - title: "Injected Todo", - order: null, - completed: false, - url: "http://todo-backend-express-knex.herokuapp.com/916", - }, - ], - { - statusCode: 404, - headers: { - "x-custom-header": "foobar", - }, - }, - ); -}); +## События {/* #events */} -it("should modify text assets", async ({ browser }) => { - const scriptMock = await browser.mock("**" + "/script.min.js"); - scriptMock.respond("./tests/fixtures/script.js"); -}); +Подписывайтесь через `mock.on(name, listener)`. Обработчик выполняется в Node.js, а не в браузере. + +| Событие | BiDi | Classic/CDP | +| ----------- | --------------------------------------------------------------- | ------------------------------------- | +| `request` | Событие `network.beforeRequestSent`: URL в `event.request.url`. | Событие CDP `Fetch.requestPaused`. | +| `match` | В этой версии не испускается, хотя объявлено в типах. | Запись совпавшего ответа. | +| `overwrite` | Событие запроса или ответа, к которому применена подмена. | Параметры подмененного ответа. | +| `fail` | Идентификатор прерванного запроса. | Объект с `requestId` и `errorReason`. | +| `continue` | Идентификатор продолженного запроса. | Идентификатор продолженного запроса. | -it("should redirect web resources", async ({ browser }) => { - const headerMock = await browser.mock("**" + "/header.png"); - headerMock.respond("https://media.giphy.com/media/F9hQLAVhWnL56/giphy.gif"); +Не используйте наличие события как доказательство завершения всего сетевого обмена. - const pageMock = await browser.mock("https://google.com/"); - pageMock.respond("https://webdriver.io"); - await browser.url("https://google.com"); +## Пример {/* #examples */} - console.log(await browser.getTitle()); - // выведет: "WebdriverIO · Next-gen browser and mobile automation test framework for Node.js" +Пример использует Chrome с WebDriver BiDi. Укажите в `baseUrl` адрес тестового HTTP-сервера: `/` отдает HTML-страницу, а `/api/items` — JSON с полем `source: "original"` и статусом `200`. Явная подписка на события нужна для новых сессий в одном воркере в WDIO 9.6.2. + +```javascript testplane=related-mock +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(); + } }); ``` ## Связанные команды {/* #related */} -- [mockClearAll](../mockClearAll) -- [mockRestoreAll](../mockRestoreAll) +- [mockClearAll](./mockClearAll.mdx) +- [mockRestoreAll](./mockRestoreAll.mdx) +- [respond](../mock/respond.mdx) + +## Источники {/* #references */} -[how-to-use-cdp]: ../../../guides/how-to-use-cdp -[how-to-intercept-requests-and-responses]: ../../../guides/how-to-intercept-requests-and-responses +Материал учитывает [исходную статью WebdriverIO](https://webdriver.io/docs/api/browser/mock). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/restore.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/restore.mdx new file mode 100644 index 00000000..c3621707 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/restore.mdx @@ -0,0 +1,53 @@ +# restore + +## Обзор {/* #overview */} + +Отмените эмуляцию, включенную через `emulate` у того же объекта браузера. Команда не восстанавливает cookies, хранилища, ограничение сети или CPU и не отменяет моки. + +## Использование {/* #usage */} + +`await browser.restore()` или `await browser.restore(scopes)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------ | -------------------- | ----------------------------- | ------------------------------------------------------------------------------- | +| `scopes` | `string \| string[]` | Все зарегистрированные режимы | Один или несколько режимов: clock, geolocation, userAgent, colorScheme, onLine. | + +## Результат {/* #result */} + +`Promise`. Если для объекта браузера не записана эмуляция, команда ничего не делает. + +## Ограничения {/* #limitations */} + +Для каждой подмены выберите один способ очистки: вызовите функцию, которую вернул `emulate`, **или** выполните `browser.restore(scope)` в `finally` того же теста. Не вызывайте дополнительно `browser.restore()` для уже снятой подмены: в `@testplane/webdriverio` 9.6.2 команда может попытаться удалить тот же скрипт второй раз. Чтобы увидеть исходное значение свойства, которое изменил скрипт при загрузке, перезагрузите страницу. + +`device` не входит в список режимов восстановления. Вызовите функцию из `emulate("device", name)`: она снимет подмену user agent и установит размеры Desktop Chrome (1280 × 720, DPR 1), а не прежние размеры. + +## Пример {/* #examples */} + +Настройте `baseUrl` на свой локальный тестовый HTTP-сайт, где `/` возвращает HTML-страницу. Пример выполняется внутри обычного файла тестов Testplane. + +```javascript testplane=browser-restore +const assert = require("node:assert/strict"); + +it("restore: remove a user-agent override", async ({ browser }) => { + await browser.url("/"); + const original = await browser.execute(() => navigator.userAgent); + await browser.emulate("userAgent", "ExampleBrowser/1.0"); + try { + await browser.url("/"); + assert.equal(await browser.execute(() => navigator.userAgent), "ExampleBrowser/1.0"); + } finally { + await browser.restore("userAgent"); + } + await browser.url("/"); + assert.equal(await browser.execute(() => navigator.userAgent), original); +}); +``` + +## См. также {/* #see-also */} + +- [emulate](./emulate.mdx) +- [restoreState](./restoreState.mdx) +- [mock.restore](../mock/restore.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/setViewport.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/setViewport.mdx new file mode 100644 index 00000000..5bf07cb8 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/setViewport.mdx @@ -0,0 +1,56 @@ +# setViewport + +## Обзор {/* #overview */} + +Задайте размер области отображения страницы и плотность пикселей. В отличие от `setWindowSize`, команда изменяет viewport страницы, а не внешние размеры окна браузера. + +## Использование {/* #usage */} + +`browser.setViewport({ width, height, devicePixelRatio })` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------------ | -------- | ---------------- | -------------------------------------------------------------------------- | +| `width` | `number` | Обязателен | Ширина viewport в CSS-пикселях. | +| `height` | `number` | Обязателен | Высота viewport в CSS-пикселях. | +| `devicePixelRatio` | `number` | 1 | Плотность пикселей (DPR). Если параметр не передан, устанавливается DPR 1. | + +## Результат {/* #result */} + +`Promise`. + +## Ограничения {/* #limitations */} + +Нужны WebDriver BiDi (`webSocketUrl: true`) и драйвер, который поддерживает изменение области отображения. Вызывайте команду из основного документа. Если тест переключился в iframe, сначала вернитесь через [switchFrame(null)](./switchFrame.mdx). + +Задавайте целые размеры в CSS-пикселях и положительный DPR. В `@testplane/webdriverio` 9.6.2 клиент сравнивает ширину и высоту с 0 и `Number.MAX_SAFE_INTEGER`, но драйвер может отклонить и значение внутри этого диапазона. Для восстановления сохраните не только ширину и высоту, но и DPR. Изменение области отображения не включает сенсорный ввод и не меняет движок браузера. + +## Пример {/* #examples */} + +Настройте `baseUrl` на свой локальный тестовый HTTP-сайт, где `/` возвращает HTML-страницу. Пример выполняется внутри обычного файла тестов Testplane. + +```javascript testplane=browser-set-viewport +const assert = require("node:assert/strict"); + +it("setViewport: change page dimensions", async ({ browser }) => { + await browser.url("/"); + const original = await browser.execute(() => ({ + width: innerWidth, + height: innerHeight, + devicePixelRatio, + })); + try { + await browser.setViewport({ width: 800, height: 600, devicePixelRatio: 2 }); + const viewport = await browser.execute(() => [innerWidth, innerHeight, devicePixelRatio]); + assert.deepEqual(viewport, [800, 600, 2]); + } finally { + await browser.setViewport(original); + } +}); +``` + +## См. также {/* #see-also */} + +- [setWindowSize](./setWindowSize.mdx) +- [emulate](./emulate.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/switchFrame.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/switchFrame.mdx new file mode 100644 index 00000000..5f3fe8dd --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/switchFrame.mdx @@ -0,0 +1,57 @@ +# switchFrame + +## Обзор {/* #overview */} + +Переключите последующие команды браузера в iframe или вернитесь в корневой документ. Команда изменяет контекст фрейма, а не выбранное окно. + +## Использование {/* #usage */} + +`browser.switchFrame(context)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------ | --------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `context` | `Element \| string \| Function \| null` | Обязателен | Элемент iframe; для BiDi также ID контекста, URL, часть URL или функция-предикат, выполняемая во фреймах. null выбирает корневой документ. | + +## Результат {/* #result */} + +`Promise`. В режиме BiDi возвращается ID выбранного контекста. В Classic протокольное переключение может не возвращать значение. + +## Ограничения {/* #limitations */} + +Classic поддерживает элемент iframe и `null`, но отклоняет строку и функцию. Для перехода между соседними фреймами сначала вернитесь в основной документ через `await browser.switchFrame(null)`, затем найдите следующий iframe. Используйте `finally`, если дальнейшие шаги теста должны выполняться в основном документе. Если фрейм не найден, команда завершается ошибкой. Не путайте ее с `switchWindow`. + +:::warning + +В WDIO 9.6.2 ветка с функцией-предикатом обращается к глобальному `browser`. В стандартном тесте Testplane с аргументом `{ browser }` подходящий фрейм найден, но команда завершается ошибкой `browser is not defined`. Это воспроизведено в BiDi-сессии. Используйте элемент iframe, как в примере ниже; не создавайте глобальный `browser` ради обхода ошибки. + +::: + +## Пример {/* #examples */} + +Настройте `baseUrl` на свой локальный тестовый HTTP-сайт, где `/` возвращает HTML-страницу. Пример выполняется внутри обычного файла тестов Testplane. + +```javascript testplane=browser-switch-frame +const assert = require("node:assert/strict"); + +it("switchFrame: enter an iframe and return", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = + '

Main page

'; + }); + try { + await browser.switchFrame(browser.$("#frame")); + assert.equal(await browser.$("p").getText(), "Frame content"); + } finally { + await browser.switchFrame(null); + } + assert.equal(await browser.$("h1").getText(), "Main page"); +}); +``` + +## См. также {/* #see-also */} + +- [switchWindow](./switchWindow.mdx) +- [execute](./execute.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/throttle.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/throttle.mdx index fde56ecd..38b0cb8c 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/throttle.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/throttle.mdx @@ -1,69 +1,49 @@ -import Admonition from "@theme/Admonition"; - # throttle ## Обзор {/* #overview */} -Используйте команду `throttle`, чтобы эмулировать разные типы сетевого соединения у пользователя. +Устаревшее имя [throttleNetwork](./throttleNetwork.mdx). Ограничивает пропускную способность сети через CDP/Puppeteer; не эквивалентно [emulate("onLine")](./emulate.mdx). Для нового кода используйте `throttleNetwork`. -Эта команда позволяет промоделировать поведение сайта или веб-приложения при различной пропускной способности канала связи у пользователя. +## Использование {/* #usage */} -Существует также множество пресетов с готовыми настройками конфигурации сети. Например: +`await browser.throttle(profile)` -- offline | online -- GPRS -- Regular2G | Good2G -- Regular3G | Good3G -- Regular4G -- DSL -- WiFi +## Параметры команды {/* #parameters */} - -Команда _throttle_ работает только при использовании _Chrome DevTools Protocol (CDP)_. +Параметры совпадают с [throttleNetwork](./throttleNetwork.mdx#parameters). Можно передать имя профиля: `offline`, `online`, `GPRS`, `Regular2G`, `Good2G`, `Regular3G`, `Good3G`, `Regular4G`, `DSL`, `WiFi`. Пробелов в именах нет. -Читайте подробности в разделе «[Как использовать Chrome DevTools Protocol в testplane][how-to-use-cdp]». +Или объект с полями `offline` (boolean), `latency` (миллисекунды), `downloadThroughput` и `uploadThroughput` (байты в секунду, `-1` отключает ограничение скорости). Результат — `Promise`. -А также читайте рецепт «[Как управлять пропускной способностью сети][how-to-manage-network-bandwidth]». +## Ограничения {/* #limitations */} - +Нужен браузер с доступным CDP/Puppeteer. Реализация выбирает первую страницу Puppeteer: для примера используйте одну вкладку и `isolation: false`, сначала откройте страницу. -## Использование {/* #usage */} +В Testplane 9.3.2 / WDIO 9.6.2 / Chrome 150 профиль `online` не восстановил сеть после `offline`. Настройте `testsPerSession: 1`, чтобы ограничение не перешло в следующий тест. Подробнее — [throttleNetwork](./throttleNetwork.mdx#limitations). -```javascript -await browser.throttle({ offline, latency, downloadThroughput, uploadThroughput }); -``` +## Пример {/* #examples */} -## Параметры команды {/* #parameters */} +Укажите в `baseUrl` адрес тестового HTTP-сервера, который отвечает `200` на корневой путь. Пример использует новую сессию на каждый тест. + +```javascript testplane=related-throttle +const assert = require("node:assert/strict"); - - - - - - - - - - - -
**Имя****Тип****Описание**
offlineBooleanВключить эмуляцию потери соединения.
latencyNumberМинимальная задержка от отправленного запроса до полученных заголовков ответа, в миллисекундах.
downloadThroughputNumberМаксимальная совокупная пропускная способность загрузки (байт/сек). _-1_ отключает регулирование загрузки.
uploadThroughputNumberМаксимальная совокупная пропускная способность аплоада (байт/сек). _-1_ отключает регулирование аплоада.
- -## Примеры использования {/* #examples */} - -```javascript -it("should throttle the network", async ({ browser }) => { - // используем готовый пресет - await browser.throttle("Regular 3G"); - - // а здесь настраиваем конфигурацию сети сами - await browser.throttle({ - offline: false, - downloadThroughput: (200 * 1024) / 8, - uploadThroughput: (200 * 1024) / 8, - latency: 20, - }); +it("throttle: use the deprecated alias in an isolated session", async ({ browser }) => { + await browser.url("/"); + await browser.throttle("Good3G"); + const status = await browser.execute( + async () => (await fetch("/?throttled", { cache: "no-store" })).status, + ); + assert.equal(status, 200); }); ``` -[how-to-use-cdp]: ../../../guides/how-to-use-cdp -[how-to-manage-network-bandwidth]: ../../../basic-guides/emulation +## Связанные команды {/* #related */} + +- [throttleNetwork](./throttleNetwork.mdx) +- [throttleCPU](./throttleCPU.mdx) +- [CDP](../../guides/how-to-use-cdp.mdx) +- [Emulation](../../basic-guides/user-environment-emulation.mdx) + +## Источники {/* #references */} + +Материал учитывает [исходную статью WebdriverIO](https://webdriver.io/docs/api/browser/throttle). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/throttleCPU.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/throttleCPU.mdx new file mode 100644 index 00000000..fe75790b --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/throttleCPU.mdx @@ -0,0 +1,49 @@ +# throttleCPU + +## Обзор {/* #overview */} + +Замедлите CPU через Chrome DevTools Protocol. Это позволяет проверить страницу при ограниченной производительности, но не воспроизводит конкретное физическое устройство. + +## Использование {/* #usage */} + +`browser.throttleCPU(factor)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------ | -------- | ---------------- | -------------------------------------------------------------------------------- | +| `factor` | `number` | Обязателен | Коэффициент замедления: 1 отключает ограничение, 2 задает двукратное замедление. | + +## Результат {/* #result */} + +`Promise`. + +## Ограничения {/* #limitations */} + +Требуются Chromium и доступное соединение Puppeteer/CDP. Текущая реализация выбирает первую страницу Puppeteer, которая не обязательно совпадает с активной страницей Testplane. Для примера используйте одну вкладку, `isolation: false` и `testsPerSession: 1`: новая сессия сохраняет независимость тестов. Нечисловой аргумент или недоступное CDP-соединение вызывают ошибку. Коэффициент 1 запрашивает обычный режим CPU. + +## Пример {/* #examples */} + +Настройте `baseUrl` на свой локальный тестовый HTTP-сайт, где `/` возвращает HTML-страницу. Пример выполняется внутри обычного файла тестов Testplane. + +```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("/"); + try { + await browser.throttleCPU(2); + await browser.execute(() => { + document.body.innerHTML = ""; + }); + assert.equal(await browser.$("button").getText(), "Ready"); + } finally { + await browser.throttleCPU(1); + } +}); +``` + +## См. также {/* #see-also */} + +- [throttleNetwork](./throttleNetwork.mdx) +- [getPuppeteer](./getPuppeteer.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/throttleNetwork.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/throttleNetwork.mdx new file mode 100644 index 00000000..8311423d --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/throttleNetwork.mdx @@ -0,0 +1,71 @@ +# throttleNetwork + +## Обзор {/* #overview */} + +Ограничьте пропускную способность и задержку сети или переведите страницу в офлайн через CDP. Это влияет на реальные запросы, в отличие от `emulate("onLine", false)`, который меняет только JavaScript-свойство. + +## Использование {/* #usage */} + +`browser.throttleNetwork(profileOrOptions)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| -------------------- | ------------------ | -------------------- | ------------------------------------------------------------------------------------------------ | +| `profileOrOptions` | `string \| object` | Обязателен | Именованный профиль или объект с полями offline, latency, downloadThroughput и uploadThroughput. | +| `offline` | `boolean` | Обязателен в объекте | Отключен ли сетевой доступ. | +| `latency` | `number` | Обязателен в объекте | Минимальная задержка в миллисекундах. | +| `downloadThroughput` | `number` | Обязателен в объекте | Скорость скачивания в байтах в секунду; -1 снимает это ограничение. | +| `uploadThroughput` | `number` | Обязателен в объекте | Скорость отправки в байтах в секунду; -1 снимает это ограничение. | + +## Результат {/* #result */} + +`Promise`. + +## Ограничения {/* #limitations */} + +Локальная CDP-реализация требует Chromium и соединение Puppeteer. Она выбирает первую страницу Puppeteer. Для примера ниже используйте одну вкладку, `isolation: false` и `testsPerSession: 1`. Загрузите страницу до отключения сети. Профили: `offline`, `GPRS`, `Regular2G`, `Good2G`, `Regular3G`, `Good3G`, `Regular4G`, `DSL`, `WiFi`, `online`. Неизвестное имя профиля вызывает ошибку. В сессиях Sauce Labs используется отдельная команда сервиса. + +:::warning + +В проверенной связке Testplane 9.3.2, WDIO 9.6.2 и Chrome for Testing 150.0.7871.124 повторный вызов с `"online"` не восстановил сеть после `"offline"`. Каждый вызов создает отдельную CDP-сессию. Не полагайтесь на такой сброс для повторного использования браузера: пример завершает офлайн-сессию после теста и проверяет сеть в новой. Для переключения в пределах одного теста управляйте режимами через одну CDP-сессию. + +::: + +## Пример {/* #examples */} + +Настройте `baseUrl` на свой локальный тестовый HTTP-сайт, где `/` возвращает HTML-страницу. Пример выполняется внутри обычного файла тестов Testplane. + +```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); +}); + +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); +}); +``` + +## См. также {/* #see-also */} + +- [throttleCPU](./throttleCPU.mdx) +- [emulate](./emulate.mdx) +- [getPuppeteer](./getPuppeteer.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/unstable_captureDomSnapshot.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/unstable_captureDomSnapshot.mdx new file mode 100644 index 00000000..bac29d4d --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/unstable_captureDomSnapshot.mdx @@ -0,0 +1,81 @@ +# unstable_captureDomSnapshot + +## Обзор {/* #overview */} + +Создает компактное текстовое представление текущего документа или выбранного поддерева для диагностики. Чтобы снять документ с настройками, передайте объект настроек единственным аргументом. + +## Использование {/* #usage */} + +`browser.unstable_captureDomSnapshot(selector?, options?)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ----------------------- | ---------- | -------------------------- | ------------------------------------------------------------------------------------------- | +| `selector` | `string` | `body` / `documentElement` | Необязательный CSS-селектор корня снимка. Без него обход начинается с body документа. | +| `options.includeTags` | `string[]` | `[]` | Убрать имена из стандартного набора исключенных тегов; это не список разрешенных тегов. | +| `options.excludeTags` | `string[]` | `[]` | Исключить элементы вместе с поддеревьями; приоритет выше includeTags. | +| `options.includeAttrs` | `string[]` | `[]` | Добавить имена в набор сохраняемых атрибутов. | +| `options.excludeAttrs` | `string[]` | `[]` | Убрать имена из набора сохраняемых атрибутов; приоритет выше includeAttrs. | +| `options.truncateText` | `boolean` | `true` | Сокращать непосредственный текст элемента. Флаг не отключает сокращение значений атрибутов. | +| `options.maxTextLength` | `number` | `100` | Максимальная длина текста или значения атрибута до добавления `...`. | + +## Результат {/* #result */} + +`Promise` с четырьмя полями: + +- `snapshot`: компактный текст с отступами, а не HTML. +- `omittedTags`: отсортированные имена исключенных тегов, встретившихся при обходе. +- `omittedAttributes`: отсортированные имена пропущенных атрибутов сохраненных элементов. +- `textWasTruncated`: был ли сокращен текст или значение атрибута. + +Для отсутствующего CSS-совпадения возвращается `snapshot: "# Element not found: "`; для некорректного CSS — `"# Invalid selector: "`. В этих случаях ошибка селектора не выбрасывается. Списки описывают конкретный обход, а не всех пропущенных потомков. + +`maxTextLength` не ограничивает `id`, `class` и значения маркеров состояния, например `@value`. Исключенные `id` и `class` не перечисляются в `omittedAttributes`. + +## Ограничения {/* #limitations */} + +По умолчанию исключены `head`, `link`, `meta`, `noscript`, `script`, `slot`, `style`, `template` и `title`. Регистр имен тегов не учитывается. Сохраняются в том числе идентификаторы, классы, атрибуты форм, часть ARIA-атрибутов и тестовые атрибуты. Остальные добавляются через `includeAttrs`. Скрытые сохраненные элементы помечаются `@hidden`; пустые неинформативные элементы и дочерние узлы SVG могут быть пропущены. Это не полный DOM и не дерево доступности. + +Снимок может содержать значения полей ввода, текст страницы и чувствительные атрибуты. `excludeAttrs` — не универсальное средство удаления секретов: текущее значение input записывается также как `@value`. Используйте нечувствительные тестовые данные и проверяйте снимок перед добавлением в логи или отчеты. + +:::warning + +Это нестабильный API Testplane. Сигнатура, поведение и формат результата могут изменяться между версиями. + +::: + +## Пример {/* #examples */} + +Настройте `baseUrl` на локальный HTTP-сайт, где `/` возвращает HTML-страницу. Запустите пример в файле тестов Testplane. + +```javascript testplane=testplane-browser-unstable-capture-dom-snapshot +const assert = require("node:assert/strict"); + +it("browser.unstable_captureDomSnapshot: capture a filtered subtree", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = + '

abcdefghijk

Outside

'; + }); + const result = await browser.unstable_captureDomSnapshot("#panel", { + excludeAttrs: ["data-internal"], + maxTextLength: 6, + }); + assert.match(result.snapshot, /section#panel/); + assert.match(result.snapshot, /abcdef\.\.\./); + assert.doesNotMatch(result.snapshot, /Outside|data-internal/); + assert.ok(result.omittedTags.includes("script")); + assert.ok(result.omittedAttributes.includes("data-internal")); + assert.equal(result.textWasTruncated, true); + const missing = await browser.unstable_captureDomSnapshot("#missing"); + assert.equal(missing.snapshot, "# Element not found: #missing"); + const invalid = await browser.unstable_captureDomSnapshot("["); + assert.equal(invalid.snapshot, "# Invalid selector: ["); +}); +``` + +## См. также {/* #see-also */} + +- [element.unstable_captureDomSnapshot](../element/unstable_captureDomSnapshot.mdx) +- [execute](./execute.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/unstable_getCdp.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/unstable_getCdp.mdx new file mode 100644 index 00000000..6c4f34ce --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/unstable_getCdp.mdx @@ -0,0 +1,49 @@ +# unstable_getCdp + +## Обзор {/* #overview */} + +Возвращает существующее подключение Testplane к Chrome DevTools Protocol для расширенной диагностики. Это объект `CDP` Testplane, а не браузер Puppeteer или его `CDPSession`. + +## Использование {/* #usage */} + +`browser.unstable_getCdp()` + +## Параметры {/* #parameters */} + +У команды нет параметров. + +## Результат {/* #result */} + +`Promise`. Возвращает `null` для не-Chromium-сессии или если Testplane не смог создать CDP-подключение. + +## Ограничения {/* #limitations */} + +Проверяйте результат на `null`. `cdp.request(method, params?, cdpSessionId?)` отправляет протокольный запрос; командам страницы может потребоваться идентификатор сессии подключенной цели. Доступны вспомогательные объекты `target`, `runtime`, `network`, `page`, `dom`, `css`, `fetch`, `debugger` и `profiler`. Их контракты также нестабильны. Не вызывайте `cdp.close()`: это общее подключение принадлежит Testplane и используется им. Не меняйте состояние доменов, занятых раннером, без понимания взаимодействия. + +:::warning + +Это нестабильный API Testplane. Сигнатура, поведение и формат результата могут изменяться между версиями. + +::: + +## Пример {/* #examples */} + +Запустите тест в Chromium-браузере с доступным CDP-подключением. Он читает данные о версии браузера, не меняет страницу и не закрывает общее подключение. + +```javascript testplane=testplane-browser-unstable-get-cdp +const assert = require("node:assert/strict"); + +it("unstable_getCdp: query the connected Chromium browser", async ({ browser }) => { + const cdp = await browser.unstable_getCdp(); + assert.ok(cdp, "This test requires a Chromium session with a CDP connection"); + const version = await cdp.request("Browser.getVersion"); + assert.match(version.product, /Chrome/); + assert.equal(typeof version.protocolVersion, "string"); + // Testplane owns this connection: do not call cdp.close(). +}); +``` + +## См. также {/* #see-also */} + +- [getPuppeteer](./getPuppeteer.mdx) +- [execute](./execute.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/url.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/url.mdx index 74b1c782..2101bf8f 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/url.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/browser/url.mdx @@ -2,58 +2,74 @@ ## Обзор {/* #overview */} -Используйте команду `url`, чтобы перейти по заданному URL-адресу в браузере. +Открывает URL. В Testplane вызов без аргумента или с пустой строкой возвращает текущий URL и не выполняет переход. Повторный переход на тот же адрес перезагружает страницу. -Если в конфигурации указан [baseUrl][base-url], то он будет добавлен к параметру `url` с помощью метода Node.JS [url.resolve()][url-resolve]. - -Вызов `browser.url()` с тем же URL-адресом, что и в прошлый раз, вызовет перезагрузку страницы. +Если задан [baseUrl](../../reference/config/browsers.mdx#base_url), адрес разрешается через `url.resolve(baseUrl, url)`. Например, при `baseUrl` равном `http://example.com/site/` адрес `relative` откроет `/site/relative`, а `/rootRelative` — `/rootRelative`. Полный URL не зависит от `baseUrl`. Завершающий `/` в базовом адресе влияет на разрешение относительного пути. ## Использование {/* #usage */} -```javascript -await browser.url(url); -``` +`await browser.url(url, options)`; `await browser.url()` ## Параметры команды {/* #parameters */} - - - - - - - - -
**Имя****Тип****Описание**
urlStringURL, который надо открыть.
- -## Примеры использования {/* #examples */} - -**url.js** - -```javascript -// переходим на URL -await browser.url("https://webdriver.io"); - -// получаем url -console.log(await browser.getUrl()); // выведет: "https://webdriver.io" +| Параметр | Описание | +| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `url` | Строка с полным или относительным адресом. Без аргумента — чтение текущего адреса. | +| `options.wait` | BiDi: `none`, `interactive`, `complete` или `networkIdle`. Без значения используется стратегия загрузки сессии; для обычной стратегии — `complete`. Ограничение `networkIdle` описано ниже. | +| `options.timeout` | BiDi: тайм-аут только ожидания `networkIdle`, по умолчанию `5000` мс. Не заменяет тайм-ауты Testplane и загрузки страницы. | +| `options.headers` | BiDi: объект заголовков для запроса навигации. Не задает постоянные заголовки для всех ресурсов страницы. | +| `options.auth` | BiDi: объект `{ user, pass }` для HTTP Basic Auth. Заменяет `Authorization` из `headers`. Используйте HTTPS и не сохраняйте секреты в тестах. | +| `options.onBeforeLoad` | BiDi: функция, выполняемая до скриптов нового документа. Функция сериализуется и не имеет доступа к замыканию Node.js. | + +## Ограничения {/* #limitations */} + +Опции применяются только к HTTP(S)-переходам в BiDi. В Classic обертка Testplane игнорирует второй аргумент. После успешного перехода временный init-скрипт удаляется; его изменения в загруженной странице остаются до следующей навигации. + +В проверенной связке Testplane 9.3.2 / WDIO 9.6.2 / Chrome 150 режим `networkIdle` падает с `Couldn't find request for navigation with id ...`: реализация ищет запрос навигации по идентификатору контекста. Используйте `complete` и затем явно ожидайте нужное состояние приложения. `complete` само по себе не означает завершения фоновых запросов приложения. + +## Результат {/* #result */} + +Вызов без адреса возвращает строку текущего URL. Переход в Classic возвращает `undefined`; в BiDi может вернуть данные запроса навигации или `undefined`. Для чтения адреса используйте `getUrl()` или `url()` без аргумента. + +## Пример {/* #examples */} + +Пример использует Chrome/BiDi и тестовый HTTP-сервер в `baseUrl`. На `/navigation` скрипт страницы записывает `window.initialSeed = window.navigationSeed ?? null`, а сервер встраивает значение заголовка `x-example` в `window.receivedHeader`. Корневой путь отдает обычную HTML-страницу. + +```javascript testplane=related-url +const assert = require("node:assert/strict"); + +it("url: navigate with BiDi options and read the current URL", async ({ browser }) => { + await browser.url("/"); + const target = new URL("/navigation", await browser.getUrl()).href; + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + await browser.url(target, { + wait: "complete", + headers: { "x-example": "navigation" }, + onBeforeLoad: () => { + window.navigationSeed = 42; + }, + }); + assert.equal(await browser.url(), target); + assert.deepEqual(await browser.execute(() => [window.initialSeed, window.receivedHeader]), [ + 42, + "navigation", + ]); + await browser.execute(() => { + window.unsavedValue = "temporary"; + }); + await browser.url(target); + assert.equal(await browser.execute(() => typeof window.unsavedValue), "undefined"); + assert.equal(await browser.execute(() => window.initialSeed), null); +}); ``` -**baseUrlResolutions.js** - -```javascript -// Пусть baseUrl = http://example.com/site/ важно указывать слэш в конце +## Связанные команды {/* #related */} -// При указании полного URL-адреса итоговый URL будет https://webdriver.io -await browser.url("https://webdriver.io"); +- [addInitScript](./addInitScript.mdx) +- [waitUntil](./waitUntil.mdx) -// При указании URL-адреса без начального слэша -// итоговый URL формируется относительно всего baseUrl: http://example.com/site/relative -await browser.url("relative"); - -// При указании URL-адреса с начальным слэшом -// итоговый URL формируется относительно корня baseUrl: http://example.com/rootRelative -await browser.url("/rootRelative"); -``` +## Источники {/* #references */} -[base-url]: ../../../reference/config/browsers#base_url -[url-resolve]: https://nodejs.org/api/url.html#urlresolvefrom-to +Материал учитывает [исходную статью WebdriverIO](https://webdriver.io/docs/api/browser/url). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/customDollar.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/customDollar.mdx new file mode 100644 index 00000000..8b3ca9c3 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/customDollar.mdx @@ -0,0 +1,50 @@ +# custom$ + +## Обзор {/* #overview */} + +Находит элемент пользовательской стратегией поиска. Родительский элемент передается последним аргументом стратегии. Чтобы ограничить область поиска, используйте его внутри стратегии. + +## Использование {/* #usage */} + +`element.custom$(strategyName, ...strategyArguments)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------------- | ----------- | ---------------- | ----------------------------------------------------------- | +| `strategyName` | `string` | Обязательный | Имя, зарегистрированное через `browser.addLocatorStrategy`. | +| `strategyArguments` | `unknown[]` | [] | Аргументы, передаваемые перед родительским DOM-элементом. | + +## Результат {/* #result */} + +Объект элемента, получаемый через `await`. Если стратегия вернула массив, используется первый элемент. У результата без совпадения нет `elementId`. + +## Ограничения {/* #limitations */} + +Зарегистрируйте стратегию у того же объекта браузера. Родитель должен существовать; неизвестная стратегия или отсутствие родителя вызывают ошибку. Функция выполняется в браузере и возвращает DOM-элемент или массив DOM-элементов. Преобразуйте `NodeList` через `Array.from`. Область поиска определяет сама функция: `document.querySelector` продолжает искать по всему документу. Команда не ожидает заданного количества дочерних элементов или их видимости. + +## Пример {/* #examples */} + +Настройте `baseUrl` на локальный HTTP-сайт, где `/` возвращает HTML-страницу. Запустите пример в файле тестов Testplane. + +```javascript testplane=element-custom-dollar +const assert = require("node:assert/strict"); + +it("element.custom$: search inside an element", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = + '
'; + }); + browser.addLocatorStrategy("byTestWithin", (value, root) => + root.querySelector(`[data-test="${value}"]`), + ); + const button = await browser.$("#panel").custom$("byTestWithin", "save"); + assert.equal(await button.getText(), "Inside"); +}); +``` + +## См. также {/* #see-also */} + +- [addLocatorStrategy](../browser/addLocatorStrategy.mdx) +- [browser.custom$](../browser/customDollar.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/customDollarDollar.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/customDollarDollar.mdx new file mode 100644 index 00000000..017ff698 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/customDollarDollar.mdx @@ -0,0 +1,51 @@ +# custom$$ + +## Обзор {/* #overview */} + +Находит элементы пользовательской стратегией поиска. Родительский элемент передается последним аргументом стратегии. Чтобы ограничить область поиска, используйте его внутри стратегии. + +## Использование {/* #usage */} + +`element.custom$$(strategyName, ...strategyArguments)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------------- | ----------- | ---------------- | ----------------------------------------------------------- | +| `strategyName` | `string` | Обязательный | Имя, зарегистрированное через `browser.addLocatorStrategy`. | +| `strategyArguments` | `unknown[]` | [] | Аргументы, передаваемые перед родительским DOM-элементом. | + +## Результат {/* #result */} + +Массив объектов элементов, получаемый через `await`. Если стратегия ничего не нашла, массив пуст. + +## Ограничения {/* #limitations */} + +Зарегистрируйте стратегию у того же объекта браузера. Родитель должен существовать; неизвестная стратегия или отсутствие родителя вызывают ошибку. Функция выполняется в браузере и возвращает DOM-элемент или массив DOM-элементов. Преобразуйте `NodeList` через `Array.from`. Область поиска определяет сама функция: `document.querySelector` продолжает искать по всему документу. Команда не ожидает заданного количества дочерних элементов или их видимости. + +## Пример {/* #examples */} + +Настройте `baseUrl` на локальный HTTP-сайт, где `/` возвращает HTML-страницу. Запустите пример в файле тестов Testplane. + +```javascript testplane=element-custom-dollar-dollar +const assert = require("node:assert/strict"); + +it("element.custom$$: find children with a custom strategy", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = + '

Outside

First

Second

'; + }); + browser.addLocatorStrategy("byTestWithin", (value, root) => + Array.from(root.querySelectorAll(`[data-test="${value}"]`)), + ); + const items = await browser.$("#panel").custom$$("byTestWithin", "item"); + assert.equal(items.length, 2); + assert.equal(await items[1].getText(), "Second"); +}); +``` + +## См. также {/* #see-also */} + +- [addLocatorStrategy](../browser/addLocatorStrategy.mdx) +- [browser.custom$$](../browser/customDollarDollar.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/execute.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/execute.mdx new file mode 100644 index 00000000..d1094136 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/execute.mdx @@ -0,0 +1,52 @@ +# execute + +## Обзор {/* #overview */} + +Выполняет JavaScript в браузере и передает выбранный DOM-элемент первым аргументом. Используйте метод для чтения или изменения свойств DOM, для которых нет отдельной команды. + +## Использование {/* #usage */} + +`element.execute(script, ...args)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------ | -------------------- | ---------------- | --------------------------------------------------- | +| `script` | `Function \| string` | Обязательный | Функция или тело функции для выполнения в браузере. | +| `args` | `unknown[]` | [] | Дополнительные аргументы после DOM-элемента. | + +## Результат {/* #result */} + +Промис с сериализованным результатом функции. В режиме BiDi выполнение также ожидает промис, возвращенный функцией. + +## Ограничения {/* #limitations */} + +Перед выполнением команда вызывает `waitForExist`. Код браузера не имеет доступа к переменным и импортам Node.js через замыкание; передавайте данные аргументами. Ожидание существования не гарантирует видимость или кликабельность. Асинхронный пример ниже использует WebDriver BiDi. + +## Пример {/* #examples */} + +Настройте `baseUrl` на локальный HTTP-сайт, где `/` возвращает HTML-страницу. Запустите пример в файле тестов Testplane. + +```javascript testplane=element-execute +const assert = require("node:assert/strict"); + +it("element.execute: pass the DOM element to a browser function", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = '
'; + }); + const result = await browser.$("#counter").execute(async (element, increment) => { + const count = Number(element.dataset.count) + increment; + element.dataset.count = String(count); + return { count, id: element.id }; + }, 3); + assert.deepEqual(result, { count: 7, id: "counter" }); + assert.equal(await browser.$("#counter").getAttribute("data-count"), "7"); +}); +``` + +## См. также {/* #see-also */} + +- [browser.execute](../browser/execute.mdx) +- [executeAsync](./executeAsync.mdx) +- [waitForExist](./waitForExist.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/executeAsync.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/executeAsync.mdx new file mode 100644 index 00000000..9eff12ea --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/executeAsync.mdx @@ -0,0 +1,56 @@ +# executeAsync + +## Обзор {/* #overview */} + +Выполняет браузерный скрипт с callback. DOM-элемент передается первым аргументом, а callback для передачи результата в тест — последним. + +## Использование {/* #usage */} + +`element.executeAsync(script, ...args)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------ | -------------------- | ---------------- | -------------------------------------------------------------------------------- | +| `script` | `Function \| string` | Обязательный | Функция или тело функции. Для завершения вызовите последний аргумент — callback. | +| `args` | `unknown[]` | [] | Аргументы между DOM-элементом и callback. | + +## Результат {/* #result */} + +Промис со значением, переданным в callback. Возврат значения из скрипта не заменяет вызов callback. + +## Ограничения {/* #limitations */} + +В отличие от `element.execute`, эта реализация не вызывает `waitForExist` явно; дождитесь элемента самостоятельно. В Classic-сессиях тайм-аут протокольного скрипта задается через `browser.setTimeout({ script: milliseconds })`. Ветка BiDi использует `script.callFunction` без отдельного таймера callback: не полагайтесь на тайм-аут Classic, если callback не был вызван. Всегда вызывайте callback и задавайте конечный `testTimeout` в Testplane. + +:::warning + +В поставляемом API WebdriverIO метод устарел. Для новых BiDi-тестов используйте `element.execute` с асинхронной функцией. + +::: + +## Пример {/* #examples */} + +Настройте `baseUrl` на локальный HTTP-сайт, где `/` возвращает HTML-страницу. Запустите пример в файле тестов Testplane. + +```javascript testplane=element-execute-async +const assert = require("node:assert/strict"); + +it("element.executeAsync: return data through the final callback", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = '

Ready

'; + }); + const element = await browser.$("#message"); + await element.waitForExist(); + const result = await element.executeAsync((node, prefix, done) => { + setTimeout(() => done(prefix + node.textContent), 20); + }, "Status: "); + assert.equal(result, "Status: Ready"); +}); +``` + +## См. также {/* #see-also */} + +- [execute](./execute.mdx) +- [setTimeout](../browser/setTimeout.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/getElement.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/getElement.mdx new file mode 100644 index 00000000..a0b9b1f2 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/getElement.mdx @@ -0,0 +1,45 @@ +# getElement + +## Обзор {/* #overview */} + +Получает объект элемента из цепочки команд для чтения свойств `selector`, `elementId` и других данных. + +## Использование {/* #usage */} + +`element.getElement()` + +## Параметры {/* #parameters */} + +У команды нет параметров. + +## Результат {/* #result */} + +`Promise`: текущий объект элемента с методами и метаданными. + +## Ограничения {/* #limitations */} + +Это не новый протокольный поиск, не снимок DOM и не ожидание видимости. Метод возвращает текущий объект элемента. Не считайте, что его `elementId` остается действительным после навигации или замены DOM. + +## Пример {/* #examples */} + +Настройте `baseUrl` на локальный HTTP-сайт, где `/` возвращает HTML-страницу. Запустите пример в файле тестов Testplane. + +```javascript testplane=element-get-element +const assert = require("node:assert/strict"); + +it("getElement: inspect a resolved element object", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = ''; + }); + const element = await browser.$("#save").getElement(); + assert.equal(element.selector, "#save"); + assert.equal(typeof element.elementId, "string"); + assert.equal(await element.getText(), "Save"); +}); +``` + +## См. также {/* #see-also */} + +- [$](../browser/$.mdx) +- [isExisting](./isExisting.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/isStable.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/isStable.mdx new file mode 100644 index 00000000..56086f5a --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/isStable.mdx @@ -0,0 +1,57 @@ +# isStable + +## Обзор {/* #overview */} + +Проверяет, остается ли геометрия элемента неизменной между двумя кадрами анимации. Метод обнаруживает изменение положения и размера, а не любую активность страницы. + +## Использование {/* #usage */} + +`element.isStable()` + +## Параметры {/* #parameters */} + +У команды нет параметров. + +## Результат {/* #result */} + +`Promise`: `true`, если сравниваемые свойства прямоугольника совпадают, иначе `false`. + +## Ограничения {/* #limitations */} + +Проверяйте существующий элемент на активной вкладке. Скрытый документ вызывает ошибку: кадры анимации в нем не выполняются обычным образом. Прозрачность, цвет и сетевые запросы могут меняться без изменения геометрии. Результат `true` — измерение в данный момент, а не гарантия окончания всех анимаций. + +## Пример {/* #examples */} + +Настройте `baseUrl` на локальный HTTP-сайт, где `/` возвращает HTML-страницу. Запустите пример в файле тестов Testplane. + +```javascript testplane=element-is-stable +const assert = require("node:assert/strict"); + +it("isStable: check whether element geometry changes", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = '
Box
'; + }); + const box = await browser.$("#box"); + await box.waitForExist(); + assert.equal(await box.isStable(), true); + await box.execute(node => { + node.animate([{ transform: "translateX(0)" }, { transform: "translateX(200px)" }], { + duration: 500, + iterations: Infinity, + direction: "alternate", + }); + }); + try { + assert.equal(await box.isStable(), false); + } finally { + await box.execute(node => node.getAnimations().forEach(animation => animation.cancel())); + } + assert.equal(await box.isStable(), true); +}); +``` + +## См. также {/* #see-also */} + +- [waitForStable](./waitForStable.mdx) +- [waitForExist](./waitForExist.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/unstable_captureDomSnapshot.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/unstable_captureDomSnapshot.mdx new file mode 100644 index 00000000..b9592b2f --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/unstable_captureDomSnapshot.mdx @@ -0,0 +1,55 @@ +# unstable_captureDomSnapshot + +## Обзор {/* #overview */} + +Создает компактный снимок DOM с выбранным элементом в корне. Содержимое за пределами элемента в снимок не входит. + +## Использование {/* #usage */} + +`element.unstable_captureDomSnapshot(options?)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------ | ------------------------ | ---------------- | ------------------------------------------------------------------ | +| `options` | `CaptureSnapshotOptions` | `{}` | Те же параметры фильтрации и сокращения, что у браузерной команды. | + +## Результат {/* #result */} + +`Promise` с полями `snapshot`, `omittedTags`, `omittedAttributes` и `textWasTruncated`. См. [общий формат результата](../browser/unstable_captureDomSnapshot.mdx#result). + +## Ограничения {/* #limitations */} + +Использует `element.execute` с ожиданием существования элемента. Фильтрация, сокращение и ограничения обработки чувствительных данных совпадают с [браузерной командой](../browser/unstable_captureDomSnapshot.mdx#limitations). В частности, `truncateText: false` не отключает сокращение атрибутов, а значения input не очищаются от секретов. Метод принимает настройки, а не дополнительный CSS-селектор. + +:::warning + +Это нестабильный API Testplane. Сигнатура, поведение и формат результата могут изменяться между версиями. + +::: + +## Пример {/* #examples */} + +Настройте `baseUrl` на локальный HTTP-сайт, где `/` возвращает HTML-страницу. Запустите пример в файле тестов Testplane. + +```javascript testplane=testplane-element-unstable-capture-dom-snapshot +const assert = require("node:assert/strict"); + +it("element.unstable_captureDomSnapshot: capture only this element", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = + '

Outside

'; + }); + const result = await browser.$("#panel").unstable_captureDomSnapshot({ truncateText: false }); + assert.match(result.snapshot, /section#panel/); + assert.match(result.snapshot, /button\[data-test=save\] "Save"/); + assert.doesNotMatch(result.snapshot, /Outside/); + assert.equal(result.textWasTruncated, false); +}); +``` + +## См. также {/* #see-also */} + +- [browser.unstable_captureDomSnapshot](../browser/unstable_captureDomSnapshot.mdx) +- [execute](./execute.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/waitForStable.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/waitForStable.mdx new file mode 100644 index 00000000..97af1164 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/element/waitForStable.mdx @@ -0,0 +1,54 @@ +# waitForStable + +## Обзор {/* #overview */} + +Повторяет `isStable`, пока геометрия элемента не станет стабильной. С `reverse` ожидает обратного условия — изменения геометрии. + +## Использование {/* #usage */} + +`element.waitForStable({ timeout, interval, reverse, timeoutMsg })` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------ | --------- | ----------------------- | ------------------------------------------- | +| `timeout` | `number` | `waitTimeout` (3000 ms) | Предельное время ожидания в миллисекундах. | +| `interval` | `number` | `waitInterval` (500 ms) | Интервал проверок в миллисекундах. | +| `reverse` | `boolean` | `false` | Ожидать результата `false` от `isStable()`. | +| `timeoutMsg` | `string` | — | Сообщение ошибки по тайм-ауту. | + +## Результат {/* #result */} + +`Promise`. Успешное завершение возвращает `undefined`, а не `true`. Тайм-аут или ошибка проверки стабильности отклоняют промис. + +## Ограничения {/* #limitations */} + +Значения тайм-аутов берутся из конфигурации браузера Testplane. Действуют ограничения `isStable`: активная вкладка и проверка только геометрии. Если элемент появится позже, сначала дождитесь его существования. Команда не ожидает окончания HTTP-запросов или анимаций, не затрагивающих геометрию. + +## Пример {/* #examples */} + +Настройте `baseUrl` на локальный HTTP-сайт, где `/` возвращает HTML-страницу. Запустите пример в файле тестов Testplane. + +```javascript testplane=element-wait-for-stable +const assert = require("node:assert/strict"); + +it("waitForStable: wait for a size animation to stop", async ({ browser }) => { + await browser.url("/"); + await browser.execute(() => { + document.body.innerHTML = '
Box
'; + }); + const box = await browser.$("#box"); + await box.execute(node => { + node.animate([{ width: "40px" }, { width: "140px" }], { duration: 500, fill: "forwards" }); + }); + const result = await box.waitForStable({ timeout: 3000, interval: 50 }); + assert.equal(result, undefined); + assert.equal(await box.execute(node => node.getBoundingClientRect().width), 140); +}); +``` + +## См. также {/* #see-also */} + +- [isStable](./isStable.mdx) +- [waitForExist](./waitForExist.mdx) +- [waitUntil](../browser/waitUntil.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/abort.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/abort.mdx index 7c5aeaeb..6d27c743 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/abort.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/abort.mdx @@ -2,47 +2,60 @@ ## Обзор {/* #overview */} -Используйте команду `abort`, чтобы прервать запрос с заданной ошибкой. +Прерывает подходящие запросы, пока правило активно. Сигнатуры BiDi и Classic/CDP различаются. В BiDi не передавайте строку с кодом ошибки: она не задает сетевую ошибку и может изменить однократность правила. -Запрос можно прервать с одной из следующих ошибок: +## Использование {/* #usage */} -- Failed -- Aborted -- TimedOut -- AccessDenied -- ConnectionClosed | ConnectionReset | ConnectionRefused | ConnectionAborted | ConnectionFailed -- NameNotResolved -- InternetDisconnected -- AddressUnreachable -- BlockedByClient | BlockedByResponse +**BiDi:** `mock.abort(once = false)` -## Использование {/* #usage */} +**Classic/CDP:** `mock.abort(errorReason, sticky = true)` -```javascript -mock.abort(errorCode); -``` +## Параметры и результат {/* #parameters */} + +BiDi: `once` — boolean, по умолчанию `false`; для одного запроса удобнее [abortOnce](./abortOnce.mdx). Classic/CDP: `errorReason` задает ошибку, `sticky` по умолчанию `true` сохраняет правило. -## Параметры команды {/* #parameters */} +Коды ошибки Classic/CDP: `Failed`, `Aborted`, `TimedOut`, `AccessDenied`, `ConnectionClosed`, `ConnectionReset`, `ConnectionRefused`, `ConnectionAborted`, `ConnectionFailed`, `NameNotResolved`, `InternetDisconnected`, `AddressUnreachable`, `BlockedByClient`, `BlockedByResponse`. - - - - - - +BiDi возвращает тот же объект мока синхронно; Classic/CDP не возвращает полезного значения. Правила BiDi делят очередь с [request](./request.mdx) и [redirect](./redirect.mdx). Постоянное правило заменяет очередь, однократное сохраняет другие однократные правила и убирает постоянное. В CDP правила добавляются в очередь: ранее добавленное постоянное правило может не дать примениться следующему. - -
**Имя****Тип****Описание**
errorCodeErrorCodeКод ошибки ответа. Возможные значения см. [выше](#overview).
+## Пример {/* #examples */} -## Примеры использования {/* #examples */} +Пример использует Chrome с WebDriver BiDi. Укажите в `baseUrl` адрес тестового HTTP-сервера: `/` отдает HTML-страницу, а `/api/items` — JSON с полем `source: "original"` и статусом `200`. Явная подписка на события нужна для новых сессий в одном воркере в WDIO 9.6.2. -```javascript -it("should block Google Analytics from page", async ({ browser }) => { - const mock = await browser.mock("https://www.google-analytics.com/**"); - mock.abort("Failed"); +```javascript testplane=related-abort +const assert = require("node:assert/strict"); + +it("mock.abort: block matching BiDi requests", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.abort(); + for (let i = 0; i < 2; i++) { + const failed = await browser.execute(async () => { + try { + await fetch("/api/items", { cache: "no-store" }); + return false; + } catch { + return true; + } + }); + assert.equal(failed, true); + } + } finally { + await mock.restore(); + } }); ``` ## Связанные команды {/* #related */} -- [abortOnce](../abortOnce) +- [abortOnce](./abortOnce.mdx) +- [restore](./restore.mdx) +- [browser.mock](../browser/mock.mdx) + +## Источники {/* #references */} + +Материал учитывает [исходную статью WebdriverIO](https://webdriver.io/docs/api/mock/abort). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/abortOnce.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/abortOnce.mdx index c3b10165..79e44f97 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/abortOnce.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/abortOnce.mdx @@ -2,56 +2,62 @@ ## Обзор {/* #overview */} -Используйте команду `abortOnce`, чтобы прервать запрос один раз с заданной ошибкой. - -Запрос можно прервать с одной из следующих ошибок: - -- Failed -- Aborted -- TimedOut -- AccessDenied -- ConnectionClosed | ConnectionReset | ConnectionRefused | ConnectionAborted | ConnectionFailed -- NameNotResolved -- InternetDisconnected -- AddressUnreachable -- BlockedByClient | BlockedByResponse +Прерывает следующий подходящий запрос. В BiDi вызывайте `abortOnce()` без аргументов: дополнительные аргументы не задают тип ошибки и не меняют однократность правила. В Classic/CDP передайте `errorReason`. ## Использование {/* #usage */} -```javascript -mock.abortOnce(errorCode); -``` - -## Параметры команды {/* #parameters */} - - - - - - - - - -
**Имя****Тип****Описание**
errorCodeErrorCodeКод ошибки ответа. Возможные значения см. [выше](#overview).
- -## Примеры использования {/* #examples */} - -```javascript -it("should block mock only once", async ({ browser }) => { - const mock = await browser.mock("https://webdriver.io"); - mock.abortOnce("Failed"); - - await browser - .url("https://webdriver.io") - // ловим исключение, так как запрос к странице упадет - .catch(() => console.log('Failed to get the page "https://webdriver.io"')); - - await browser.url("https://webdriver.io"); - console.log(await browser.getTitle()); - // выведет: "WebdriverIO · Next-gen browser and mobile automation test framework for Node.js" +**BiDi:** `mock.abortOnce()` + +**Classic/CDP:** `mock.abortOnce(errorReason)` + +## Параметры и результат {/* #parameters */} + +BiDi не принимает аргументов. В Classic/CDP нужен `errorReason`. + +Коды ошибки Classic/CDP: `Failed`, `Aborted`, `TimedOut`, `AccessDenied`, `ConnectionClosed`, `ConnectionReset`, `ConnectionRefused`, `ConnectionAborted`, `ConnectionFailed`, `NameNotResolved`, `InternetDisconnected`, `AddressUnreachable`, `BlockedByClient`, `BlockedByResponse`. + +BiDi возвращает тот же объект мока синхронно; Classic/CDP не возвращает полезного значения. Правила BiDi делят очередь с [request](./request.mdx) и [redirect](./redirect.mdx). Постоянное правило заменяет очередь, однократное сохраняет другие однократные правила и убирает постоянное. В CDP правила добавляются в очередь: ранее добавленное постоянное правило может не дать примениться следующему. + +## Пример {/* #examples */} + +Пример использует Chrome с WebDriver BiDi. Укажите в `baseUrl` адрес тестового HTTP-сервера: `/` отдает HTML-страницу, а `/api/items` — JSON с полем `source: "original"` и статусом `200`. Явная подписка на события нужна для новых сессий в одном воркере в WDIO 9.6.2. + +```javascript testplane=related-abort-once +const assert = require("node:assert/strict"); + +it("mock.abortOnce: block one BiDi request", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.abortOnce(); + const failed = await browser.execute(async () => { + try { + await fetch("/api/items", { cache: "no-store" }); + return false; + } catch { + return true; + } + }); + assert.equal(failed, true); + const status = await browser.execute( + async () => (await fetch("/api/items", { cache: "no-store" })).status, + ); + assert.equal(status, 200); + } finally { + await mock.restore(); + } }); ``` ## Связанные команды {/* #related */} -- [abort](../abort) +- [abort](./abort.mdx) +- [restore](./restore.mdx) +- [browser.mock](../browser/mock.mdx) + +## Источники {/* #references */} + +Материал учитывает [исходную статью WebdriverIO](https://webdriver.io/docs/api/mock/abortOnce). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/clear.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/clear.mdx index 20a005a9..3157dad7 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/clear.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/clear.mdx @@ -2,27 +2,56 @@ ## Обзор {/* #overview */} -Используйте команду `clear`, чтобы сбросить всю информацию, хранящуюся в массиве `mock.calls`. +Очищает историю `mock.calls`, но сохраняет перехватчик, правила подмены и обработчики событий. Следующий подходящий ответ снова добавится в историю. Для удаления правил без удаления BiDi-мока используйте [reset](./reset.mdx); для полного удаления — [restore](./restore.mdx). ## Использование {/* #usage */} -```javascript -mock.clear(); -``` - -## Примеры использования {/* #examples */} - -```javascript -it("should clear mock", async ({ browser }) => { - const mock = await browser.mock("https://google.com/"); - await browser.url("https://google.com"); - - console.log(mock.calls.length); // выведет: 1 - mock.clear(); - console.log(mock.calls.length); // выведет: 0 +`await mock.clear()` + +## Параметры и результат {/* #parameters */} + +Аргументов нет. BiDi синхронно возвращает тот же мок, Classic/CDP не возвращает полезного значения. В примере используется `await`, что также подходит для асинхронных реализаций. Очистите историю перед [waitForResponse](./waitForResponse.mdx), если нужно дождаться нового ответа, а не ранее сохраненного. + +## Пример {/* #examples */} + +Пример использует Chrome с WebDriver BiDi. Укажите в `baseUrl` адрес тестового HTTP-сервера: `/` отдает HTML-страницу, а `/api/items` — JSON с полем `source: "original"` и статусом `200`. Явная подписка на события нужна для новых сессий в одном воркере в WDIO 9.6.2. + +```javascript testplane=related-clear +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(); + } }); ``` ## Связанные команды {/* #related */} -- [restore](../restore) +- [reset](./reset.mdx) +- [restore](./restore.mdx) +- [browser.mock](../browser/mock.mdx) + +## Источники {/* #references */} + +Материал учитывает [исходную статью WebdriverIO](https://webdriver.io/docs/api/mock/clear). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/redirect.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/redirect.mdx new file mode 100644 index 00000000..7d1f3011 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/redirect.mdx @@ -0,0 +1,60 @@ +# redirect + +## Обзор {/* #overview */} + +Меняет URL назначения подходящих исходящих запросов. Это переопределение URL, а не HTTP-ответ 3xx или навигация браузера. + +## Использование {/* #usage */} + +`mock.redirect(redirectUrl, once = false)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------- | --------- | ---------------- | -------------------------------------------------- | +| `redirectUrl` | `string` | Обязательный | Абсолютный URL назначения. | +| `once` | `boolean` | `false` | Применить только к следующему подходящему запросу. | + +## Результат {/* #result */} + +Тот же объект мока синхронно. + +## Ограничения {/* #limitations */} + +Нужна WebDriver BiDi-сессия (`webSocketUrl: true`): в Classic/CDP-реализации мока этого метода нет. Примеры явно подписываются на сетевые события в каждой сессии; см. [ограничение подписки](./waitForResponse.mdx#limitations). Когда мок больше не нужен, вызовите `mock.restore()` в `finally`. + +Адрес назначения должен быть доступен. Перенаправления используют общую очередь с `request` и `abort`: постоянное перенаправление заменяет очередь, а однократное удаляет предыдущее постоянное правило. После однократного перенаправления запросы отправляются без изменения, если в очереди нет других однократных правил. + +## Пример {/* #examples */} + +Укажите [тестовый сайт](../overview.mdx#run-examples) в `baseUrl`. Оба запроса к `/api/items` должны попасть на `/api/other`, который возвращает JSON с `source: "redirected"`. + +```javascript testplane=mock-redirect +const assert = require("node:assert/strict"); + +it("mock.redirect: send matching requests to another endpoint", async ({ browser }) => { + await browser.url("/"); + const target = new URL("/api/other", await browser.getUrl()).href; + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.redirect(target); + for (let i = 0; i < 2; i++) { + const data = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(data.source, "redirected"); + } + } finally { + await mock.restore(); + } +}); +``` + +## См. также {/* #see-also */} + +- [redirectOnce](./redirectOnce.mdx) +- [request](./request.mdx) +- [reset](./reset.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/redirectOnce.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/redirectOnce.mdx new file mode 100644 index 00000000..a98a0a6d --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/redirectOnce.mdx @@ -0,0 +1,61 @@ +# redirectOnce + +## Обзор {/* #overview */} + +Меняет URL только у следующего подходящего запроса. Эквивалент `mock.redirect(redirectUrl, true)`. + +## Использование {/* #usage */} + +`mock.redirectOnce(redirectUrl)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------- | -------- | ---------------- | -------------------------- | +| `redirectUrl` | `string` | Обязательный | Абсолютный URL назначения. | + +## Результат {/* #result */} + +Тот же объект мока синхронно. + +## Ограничения {/* #limitations */} + +Нужна WebDriver BiDi-сессия (`webSocketUrl: true`): в Classic/CDP-реализации мока этого метода нет. Примеры явно подписываются на сетевые события в каждой сессии; см. [ограничение подписки](./waitForResponse.mdx#limitations). Когда мок больше не нужен, вызовите `mock.restore()` в `finally`. + +Адрес назначения должен быть доступен. Перенаправления используют общую очередь с `request` и `abort`: постоянное перенаправление заменяет очередь, а однократное удаляет предыдущее постоянное правило. После однократного перенаправления запросы отправляются без изменения, если в очереди нет других однократных правил. + +## Пример {/* #examples */} + +Укажите [тестовый сайт](../overview.mdx#run-examples) в `baseUrl`. `/api/items` возвращает JSON с `source: "original"`, а `/api/other` — с `source: "redirected"`. На `/api/other` должен попасть только первый запрос. + +```javascript testplane=mock-redirect-once +const assert = require("node:assert/strict"); + +it("mock.redirectOnce: redirect only the next request", async ({ browser }) => { + await browser.url("/"); + const target = new URL("/api/other", await browser.getUrl()).href; + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.redirectOnce(target); + const first = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + const second = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(first.source, "redirected"); + assert.equal(second.source, "original"); + } finally { + await mock.restore(); + } +}); +``` + +## См. также {/* #see-also */} + +- [redirect](./redirect.mdx) +- [request](./request.mdx) +- [reset](./reset.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/request.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/request.mdx new file mode 100644 index 00000000..0836d24c --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/request.mdx @@ -0,0 +1,65 @@ +# request + +## Обзор {/* #overview */} + +Изменяет подходящие исходящие запросы до отправки на сервер: заголовки, метод, тело, cookie или URL. + +## Использование {/* #usage */} + +`mock.request(overwrite, once = false)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------------- | ------------------------------------ | ---------------- | --------------------------------------------------------------------------------------------------------------- | +| `overwrite` | `object` | Обязательный | Поля запроса для переопределения. | +| `overwrite.body` | `unknown \| Function` | — | Тело запроса: строки передаются как текст, объекты — как JSON. Ложные значения тела в этой версии игнорируются. | +| `overwrite.cookies` | `Cookie[] \| Function` | — | Массив cookie в формате WebDriver. | +| `overwrite.headers` | `Record \| Function` | — | Новый набор заголовков, а не дополнение исходного. | +| `overwrite.method` | `string \| Function` | — | HTTP-метод, например `POST`. | +| `overwrite.url` | `string \| Function` | — | Абсолютный URL назначения. | +| `once` | `boolean` | `false` | Применить правило только к следующему подходящему запросу. | + +## Результат {/* #result */} + +Тот же объект мока синхронно, для цепочки вызовов. + +## Ограничения {/* #limitations */} + +Нужна WebDriver BiDi-сессия (`webSocketUrl: true`): в Classic/CDP-реализации мока этого метода нет. Примеры явно подписываются на сетевые события в каждой сессии; см. [ограничение подписки](./waitForResponse.mdx#limitations). Когда мок больше не нужен, вызовите `mock.restore()` в `finally`. + +Переопределение меняет исходящий запрос, а не создает поддельный ответ. Поле может быть значением или синхронной функцией от события BiDi (URL находится в `event.request.url`). Переопределения запросов, перенаправления и прерывания используют общую очередь правил. Постоянное правило заменяет очередь; однократное сохраняет другие однократные правила, но удаляет постоянное. Не рассчитывайте на возврат к постоянному правилу после однократного. + +## Пример {/* #examples */} + +Укажите [тестовый сайт](../overview.mdx#run-examples) в `baseUrl`. `/api/items` принимает GET и POST. Обработчик возвращает метод запроса в поле JSON `method`, а значение заголовка `x-example` — в `header`. Подмена должна сработать для обоих запросов. + +```javascript testplane=mock-request +const assert = require("node:assert/strict"); + +it("mock.request: change outgoing requests", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.request({ method: "POST", headers: { "x-example": "persistent" } }); + for (let i = 0; i < 2; i++) { + const data = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(data.method, "POST"); + assert.equal(data.header, "persistent"); + } + } finally { + await mock.restore(); + } +}); +``` + +## См. также {/* #see-also */} + +- [requestOnce](./requestOnce.mdx) +- [respond](./respond.mdx) +- [reset](./reset.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/requestOnce.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/requestOnce.mdx new file mode 100644 index 00000000..62139846 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/requestOnce.mdx @@ -0,0 +1,65 @@ +# requestOnce + +## Обзор {/* #overview */} + +Изменяет только следующий подходящий исходящий запрос. Эквивалент `mock.request(overwrite, true)`. + +## Использование {/* #usage */} + +`mock.requestOnce(overwrite)` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------------- | ------------------------------------ | ---------------- | --------------------------------------------------------------------------------------------------------------- | +| `overwrite` | `object` | Обязательный | Поля запроса для переопределения. | +| `overwrite.body` | `unknown \| Function` | — | Тело запроса: строки передаются как текст, объекты — как JSON. Ложные значения тела в этой версии игнорируются. | +| `overwrite.cookies` | `Cookie[] \| Function` | — | Массив cookie в формате WebDriver. | +| `overwrite.headers` | `Record \| Function` | — | Новый набор заголовков, а не дополнение исходного. | +| `overwrite.method` | `string \| Function` | — | HTTP-метод, например `POST`. | +| `overwrite.url` | `string \| Function` | — | Абсолютный URL назначения. | + +## Результат {/* #result */} + +Тот же объект мока синхронно, для цепочки вызовов. + +## Ограничения {/* #limitations */} + +Нужна WebDriver BiDi-сессия (`webSocketUrl: true`): в Classic/CDP-реализации мока этого метода нет. Примеры явно подписываются на сетевые события в каждой сессии; см. [ограничение подписки](./waitForResponse.mdx#limitations). Когда мок больше не нужен, вызовите `mock.restore()` в `finally`. + +Переопределение меняет исходящий запрос, а не создает поддельный ответ. Поле может быть значением или синхронной функцией от события BiDi (URL находится в `event.request.url`). Переопределения запросов, перенаправления и прерывания используют общую очередь правил. Постоянное правило заменяет очередь; однократное сохраняет другие однократные правила, но удаляет постоянное. Не рассчитывайте на возврат к постоянному правилу после однократного. + +## Пример {/* #examples */} + +Укажите [тестовый сайт](../overview.mdx#run-examples) в `baseUrl`. `/api/items` возвращает значение заголовка `x-example` в поле JSON `header` или `null`, если заголовка нет. Заголовок должен прийти только с первым запросом. + +```javascript testplane=mock-request-once +const assert = require("node:assert/strict"); + +it("mock.requestOnce: change only the next request", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.requestOnce({ headers: { "x-example": "once" } }); + const first = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + const second = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(first.header, "once"); + assert.equal(second.header, null); + } finally { + await mock.restore(); + } +}); +``` + +## См. также {/* #see-also */} + +- [request](./request.mdx) +- [respond](./respond.mdx) +- [reset](./reset.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/reset.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/reset.mdx new file mode 100644 index 00000000..8a4712cc --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/reset.mdx @@ -0,0 +1,74 @@ +# reset + +## Обзор {/* #overview */} + +Очищает историю вызовов и все правила изменения запросов и ответов, сохраняя активный перехват. Позволяет повторно использовать мок с прежним шаблоном URL и фильтрами. + +## Использование {/* #usage */} + +`mock.reset()` + +## Параметры {/* #parameters */} + +У команды нет параметров. + +## Результат {/* #result */} + +Тот же объект мока синхронно. + +## Ограничения {/* #limitations */} + +Нужна WebDriver BiDi-сессия (`webSocketUrl: true`): в Classic/CDP-реализации мока этого метода нет. Примеры явно подписываются на сетевые события в каждой сессии; см. [ограничение подписки](./waitForResponse.mdx#limitations). Когда мок больше не нужен, вызовите `mock.restore()` в `finally`. + +`clear()` удаляет только историю и сохраняет правила. `reset()` дополнительно удаляет правила, включая перенаправления и прерывания. `restore()` удаляет перехват, после чего новые переопределения у этого мока недоступны. Сброс не отменяет уже отправленный запрос или доставленный ответ. + +## Пример {/* #examples */} + +Укажите [тестовый сайт](../overview.mdx#run-examples) в `baseUrl`. `/api/items` возвращает JSON с `source: "original"` и значением заголовка `x-example` в поле `header` (`null`, если заголовка нет). Тест сбрасывает правила одного мока между запросами. + +```javascript testplane=mock-reset +const assert = require("node:assert/strict"); + +it("mock.reset: remove overrides but keep the mock usable", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + mock.request({ headers: { "x-example": "overridden" } }); + const first = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(first.header, "overridden"); + await mock.waitForResponse({ timeout: 3000 }); + assert.equal(mock.reset(), mock); + assert.equal(mock.calls.length, 0); + const second = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(second.header, null); + await mock.waitForResponse({ timeout: 3000 }); + assert.equal(mock.calls.length, 1); + mock.respond({ source: "mocked" }); + const third = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(third.source, "mocked"); + mock.reset(); + const fourth = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(fourth.source, "original"); + } finally { + await mock.restore(); + } +}); +``` + +## См. также {/* #see-also */} + +- [clear](./clear.mdx) +- [restore](./restore.mdx) +- [request](./request.mdx) +- [respond](./respond.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/respond.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/respond.mdx index 4645104f..1fd08e10 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/respond.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/respond.mdx @@ -1,85 +1,96 @@ -import Admonition from "@theme/Admonition"; - # respond ## Обзор {/* #overview */} -Используйте команду `respond`, чтобы всегда отвечать одной и той же перезаписью. - - - Читайте также рецепт «[Как отслеживать и перехватывать сетевые запросы и - ответы][how-to-intercept-requests-and-responses]». - +Подменяет ответы на подходящие запросы, пока правило активно. Исходный запрос в BiDi все равно отправляется на сервер; это не способ запретить побочные эффекты запроса. ## Использование {/* #usage */} -```javascript -mock.respond(overwrites, { header, statusCode, fetchResponse }); -``` +`mock.respond(overwrites, params)` ## Параметры команды {/* #parameters */} - - - - - - - - - - - -
**Имя****Тип****Описание**
overwritesMockOverwrite_Payload_ для перезаписи ответа.
headerObjectПерезаписать определенные заголовки.
statusCodeNumberПерезаписать код состояния ответа.
fetchResponseBooleanПолучить реальный ответ, прежде чем отвечать с помощью поддельных данных.
- -## Примеры использования {/* #examples */} - -```javascript -it('should demonstrate response overwrite with static data', async ({ browser }) => { - const mock = await browser.mock('https://todo-backend-express-knex.herokuapp.com/', { - method: 'get' - }); +| Параметр | BiDi | Classic/CDP | +| ---------------------- | --------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| `overwrites` | Строка тела или JSON-объект/массив. Callback для тела не поддерживается. | Строка, JSON или функция, получающая запись запроса и клиент. Функция может вернуть Promise. | +| `params.headers` | Заголовки ответа: объект или синхронная функция от события ответа. Заменяют набор заголовков. | Объект или функция. Дополняют исходные заголовки. | +| `params.statusCode` | Число или синхронная функция от события ответа. | Число или функция. | +| `params.cookies` | Массив `Cookie[]` в формате WebDriver или синхронная функция от события ответа. | Не поддерживается этой реализацией. | +| `params.fetchResponse` | Не применяется: подмена выполняется на стадии ответа, запрос доходит до сервера. | Boolean, по умолчанию `true`. При `false` ответ подменяется до загрузки оригинального тела. | - mock.respond([{ - title: 'Injected (non) completed Todo', - order: null, - completed: false - }, { - title: 'Injected completed Todo', - order: null, - completed: true - }], { - statusCode: 200, - fetchResponse: true // по умолчанию - }); +В `params.cookies` передавайте `value` строкой. Если нужен срок действия, укажите `expiry` (время Unix в секундах), а не `expires`. В проверенной BiDi-сессии Chrome 150 команда приняла этот параметр, но браузер не сохранил cookie. В такой конфигурации передайте заголовок ответа `Set-Cookie`, как в примере. Снятие мока не удаляет cookies из браузера. - await browser.url('https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/'); +Имя параметра — **`headers`**, не `header`. Без переопределения метаданных используются исходные значения. - await browser.$('#todo-list li').waitForExist(); +## Ограничения {/* #limitations */} - const todoElements = await browser.$$('#todo-list li'); - console.log(await Promise.all(todoElements.map(el => el.getText()))); - // выведет: "[ 'Injected (non) completed Todo', 'Injected completed Todo' ]" -}); +В BiDi (`@testplane/webdriverio` 9.6.2) вызов `mock.respond("")` оставляет исходное тело, а не возвращает пустой ответ. Непустая строка с путем к файлу или URL передается как текст ответа. Команда не читает файл и не перенаправляет запрос; для изменения URL используйте [redirect](./redirect.mdx). В Classic/CDP существующий путь читается как локальный файл, а строка с HTTP(S)-URL задает ответ-перенаправление. -it('should demonstrate response overwrite with dynamic data', async ({ browser }) => { - const mock = await browser.mock('https://todo-backend-express-knex.herokuapp.com/'); +Не смешивайте постоянные и однократные правила без учета реализации. В BiDi `respond()` заменяет очередь ответов постоянным правилом. `respondOnce()` убирает постоянное правило и добавляет однократное к другим однократным. В CDP правила добавляются в очередь, и ранее добавленное постоянное правило может перекрыть последующие. - mock.respond((request) => { - if (request.body.username === 'test') { - return { ...request.body, foo: 'bar' }; - } - return request.body; - }, { - statusCode: () => 200, - headers: () => ({ foo: 'bar }), - fetchResponse: false // не получать настоящий ответ +## Результат {/* #result */} + +BiDi синхронно возвращает тот же объект мока. Classic/CDP не возвращает полезного значения. Для удаления подмены и перехватчика вызовите `await mock.restore()`. + +## Пример {/* #examples */} + +Пример использует Chrome с WebDriver BiDi. Укажите в `baseUrl` адрес тестового HTTP-сервера: `/` отдает HTML-страницу, а `/api/items` — JSON с полем `source: "original"` и статусом `200`. Явная подписка на события нужна для новых сессий в одном воркере в WDIO 9.6.2. + +```javascript testplane=related-respond +const assert = require("node:assert/strict"); + +it("mock.respond: replace response data and metadata in BiDi", 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" }, + { + statusCode: 201, + headers: { + "content-type": "application/json", + "x-example": "response", + "set-cookie": "mock-example=ready; Path=/", + }, + }, + ); + for (let i = 0; i < 2; i++) { + const result = await browser.execute(async () => { + const response = await fetch("/api/items", { cache: "no-store" }); + return { + status: response.status, + header: response.headers.get("x-example"), + body: await response.json(), + }; + }); + assert.deepEqual(result, { + status: 201, + header: "response", + body: { source: "mocked" }, + }); + } + const [cookie] = await browser.getCookies("mock-example"); + assert.equal(cookie?.value, "ready"); + } finally { + try { + await mock.restore(); + } finally { + await browser.deleteCookies("mock-example"); + } + } }); ``` ## Связанные команды {/* #related */} -- [respondOnce](../respondOnce) +- [respondOnce](./respondOnce.mdx) +- [redirect](./redirect.mdx) +- [browser.mock](../browser/mock.mdx) +- [Перехват сетевых запросов](../../guides/how-to-intercept-requests-and-responses.mdx) + +## Источники {/* #references */} -[how-to-intercept-requests-and-responses]: ../../../guides/how-to-intercept-requests-and-responses +Материал учитывает [исходную статью WebdriverIO](https://webdriver.io/docs/api/mock/respond). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/respondOnce.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/respondOnce.mdx index 3d99842e..6a19e497 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/respondOnce.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/respondOnce.mdx @@ -1,108 +1,58 @@ -import Admonition from "@theme/Admonition"; - # respondOnce ## Обзор {/* #overview */} -Используйте команду `respondOnce`, чтобы ответить один раз заданной перезаписью. - -Вы можете вызвать `respondOnce` несколько раз подряд, тогда при запросах ответы будут использоваться в том же порядке, как были вызваны команды `respondOnce`. - -Если вы используете только `respondOnce` и обратитесь к ресурсу большее количество раз, чем вызывали `respondOnce`, то после исчерпания поддельных данных, запрос начнет возвращать оригинальный ответ от ресурса. - - - Читайте также рецепт «[Как отслеживать и перехватывать сетевые запросы и - ответы][how-to-intercept-requests-and-responses]». - +Подменяет один ответ. Несколько вызовов `respondOnce` добавляют ответы в порядке вызова. Когда очередь однократных ответов исчерпана, следующие запросы получают исходные ответы сервера. ## Использование {/* #usage */} -```javascript -mock.respondOnce(overwrites, { header, statusCode, fetchResponse }); -``` +`mock.respondOnce(overwrites, params)` ## Параметры команды {/* #parameters */} - - - - - - - - - +Параметры и их различия между BiDi и Classic/CDP совпадают с [respond](./respond.mdx#parameters), включая имя `headers`, а не `header`. В BiDi для подмены тела используйте непустую строку или JSON. Пустая строка сохраняет исходное тело. Как и в `respond`, callback тела и `fetchResponse: false` не поддерживаются. Запрос доходит до сервера. - -
**Имя****Тип****Описание**
overwritesMockOverwrite_Payload_ для перезаписи ответа.
headerObjectПерезаписать определенные заголовки.
statusCodeNumberПерезаписать код состояния ответа.
fetchResponseBooleanПолучить реальный ответ, прежде чем отвечать с помощью поддельных данных.
+В BiDi однократное правило удаляет постоянное правило и добавляется к другим однократным. В Classic/CDP ранее добавленное постоянное правило может перекрыть очередь. Не полагайтесь на одинаковое смешивание `respond` и `respondOnce` между протоколами. -## Примеры использования {/* #examples */} +BiDi синхронно возвращает тот же мок; Classic/CDP не возвращает полезного значения. -```javascript -async function getToDos(browser) { - await browser.$("#todo-list li").waitForExist(); +## Пример {/* #examples */} - const todoElements = await browser.$$("#todo-list li"); +Пример использует Chrome с WebDriver BiDi. Укажите в `baseUrl` адрес тестового HTTP-сервера: `/` отдает HTML-страницу, а `/api/items` — JSON с полем `source: "original"` и статусом `200`. Явная подписка на события нужна для новых сессий в одном воркере в WDIO 9.6.2. - return Promise.all(todoElements.map(el => el.getText())); -} +```javascript testplane=related-respond-once +const assert = require("node:assert/strict"); -it("should demonstrate the respondOnce command", async ({ browser }) => { - const mock = await browser.mock("https://todo-backend-express-knex.herokuapp.com/", { - method: "get", +it("mock.respondOnce: consume BiDi responses in order", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], }); - - mock.respondOnce([ - { - title: "3", - }, - { - title: "2", - }, - { - title: "1", - }, - ]); - - mock.respondOnce([ - { - title: "2", - }, - { - title: "1", - }, - ]); - - mock.respondOnce([ - { - title: "1", - }, - ]); - - await browser.url( - "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", - ); - console.log(await getToDos(browser)); // выведет: [ '3', '2', '1' ] - - await browser.url( - "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", - ); - console.log(await getToDos(browser)); // выведет: [ '2', '1' ] - - await browser.url( - "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", - ); - console.log(await getToDos(browser)); // выведет: [ '1' ] - - await browser.url( - "https://todobackend.com/client/index.html?https://todo-backend-express-knex.herokuapp.com/", - ); - console.log(await getToDos(browser)); // выведет: настоящий ответ ресурса + 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(); + } }); ``` ## Связанные команды {/* #related */} -- [respond](../respond) +- [respond](./respond.mdx) +- [reset](./reset.mdx) +- [restore](./restore.mdx) +- [Перехват сетевых запросов](../../guides/how-to-intercept-requests-and-responses.mdx) + +## Источники {/* #references */} -[how-to-intercept-requests-and-responses]: ../../../guides/how-to-intercept-requests-and-responses +Материал учитывает [исходную статью WebdriverIO](https://webdriver.io/docs/api/mock/respondOnce). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/restore.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/restore.mdx index 44e045cb..2e90b580 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/restore.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/restore.mdx @@ -2,27 +2,55 @@ ## Обзор {/* #overview */} -Используйте команду `restore`, чтобы выполнить все то же, что делает [mock.clear()](../clear), а также удалить любые поддельные возвращаемые значения или реализации. +Снимает сетевой перехватчик этого мока, очищает его историю и отключает правила подмены. Команда не отменяет последствий уже выполненного запроса, например не удаляет сохраненные браузером cookies. Для отмены эмуляции используйте [browser.restore](../browser/restore.mdx). -## Использование {/* #usage */} - -```javascript -mock.restore(); -``` - -## Примеры использования {/* #examples */} +Дождитесь `restore()` перед следующим запросом или завершением теста. Если нужно поменять правила для того же URL в той же BiDi-сессии, вызовите [reset](./reset.mdx) у существующего мока. В `@testplane/webdriverio` 9.6.2 обработчики прежнего мока могут получить событие запроса, остановленного новым перехватчиком. -```javascript -it("should demonstrate the addValue command", async ({ browser }) => { - const mock = await browser.mock("**/googlelogo_color_272x92dp.png"); - mock.respond("https://webdriver.io/img/webdriverio.png"); +## Использование {/* #usage */} - await browser.url("https://google.com"); // покажет логотип WebdriverIO вместо логотипа Google - mock.restore(); - await browser.url("https://google.com"); // покажет родной логотип Google +`await mock.restore()` + +## Параметры и результат {/* #parameters */} + +Аргументов нет. Возвращает Promise: в BiDi он разрешается тем же объектом мока, в Classic/CDP — без полезного значения. Используйте команду для очистки в `finally`, в том числе когда проверка теста завершилась ошибкой. + +## Пример {/* #examples */} + +Пример использует Chrome с WebDriver BiDi. Укажите в `baseUrl` адрес тестового HTTP-сервера: `/` отдает HTML-страницу, а `/api/items` — JSON с полем `source: "original"` и статусом `200`. Явная подписка на события нужна для новых сессий в одном воркере в WDIO 9.6.2. + +```javascript testplane=related-restore +const assert = require("node:assert/strict"); + +it("mock.restore: remove interception before the next request", 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" }); + const body = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(body.source, "mocked"); + } finally { + await mock.restore(); + } + const body = await browser.execute(async () => + (await fetch("/api/items", { cache: "no-store" })).json(), + ); + assert.equal(body.source, "original"); + assert.equal(mock.calls.length, 0); + assert.throws(() => mock.respond({ source: "unused" }), /restored mock/); }); ``` ## Связанные команды {/* #related */} -- [clear](../clear) +- [clear](./clear.mdx) +- [reset](./reset.mdx) +- [browser.mock](../browser/mock.mdx) + +## Источники {/* #references */} + +Материал учитывает [исходную статью WebdriverIO](https://webdriver.io/docs/api/mock/restore). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/waitForResponse.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/waitForResponse.mdx new file mode 100644 index 00000000..a646322b --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/mock/waitForResponse.mdx @@ -0,0 +1,71 @@ +# waitForResponse + +## Обзор {/* #overview */} + +Ждет, пока в `mock.calls` появится хотя бы одна запись. Если тесту важно содержимое ответа или изменение интерфейса, проверьте это отдельно. + +## Использование {/* #usage */} + +`mock.waitForResponse({ timeout, interval, timeoutMsg })` + +## Параметры {/* #parameters */} + +| **Параметр** | **Тип** | **По умолчанию** | **Описание** | +| ------------ | -------- | ----------------------- | ------------------------------------------ | +| `timeout` | `number` | `waitTimeout` (3000 ms) | Предельное время ожидания в миллисекундах. | +| `interval` | `number` | `waitInterval` (500 ms) | Интервал проверок в миллисекундах. | +| `timeoutMsg` | `string` | — | Сообщение ошибки по тайм-ауту. | + +## Результат {/* #result */} + +`Promise` со значением `true`, когда `calls` непуст. При тайм-ауте или ошибке проверки промис отклоняется. Сам ответ не возвращается: читайте `mock.calls` отдельно. + +## Ограничения {/* #limitations */} + +Предыдущая запись сразу завершит ожидание. Вызовите [clear](./clear.mdx) **до** действия, которое отправит интересующий запрос. + +- **BiDi:** запись появляется при `network.responseStarted`. Тело ответа в этот момент может быть еще не прочитано. +- **Classic/CDP:** запрос с `abort` или `respond(..., { fetchResponse: false })` может попасть в историю, даже если он не дошел до сервера. Успешное ожидание не означает, что сервер ответил. + +В `@testplane/webdriverio` 9.6.2 автоматическая подписка на события может не сработать для следующей BiDi-сессии в том же воркере. Подпишитесь на два сетевых события в каждой сессии, как в примере. + +## Пример {/* #examples */} + +На [тестовом сайте](../overview.mdx#run-examples) `/` возвращает HTML, а `/api/items` — успешный ответ. Во второй раз страница запускает `fetch` без ожидания в тесте. Сначала тест ждет записи в моке, затем — завершения чтения тела на странице. + +```javascript testplane=mock-wait-for-response +const assert = require("node:assert/strict"); + +it("mock.waitForResponse: wait for a new recorded response", async ({ browser }) => { + await browser.url("/"); + await browser.sessionSubscribe({ + events: ["network.beforeRequestSent", "network.responseStarted"], + }); + const mock = await browser.mock("/api/items"); + try { + await browser.execute(async () => (await fetch("/api/items")).text()); + await mock.waitForResponse({ timeout: 3000 }); + mock.clear(); + assert.equal(mock.calls.length, 0); + await browser.execute(() => { + window.requestFinished = false; + fetch("/api/items", { cache: "no-store" }) + .then(response => response.text()) + .then(() => { + window.requestFinished = true; + }); + }); + assert.equal(await mock.waitForResponse({ timeout: 3000, interval: 50 }), true); + assert.equal(mock.calls.length, 1); + await browser.waitUntil(() => browser.execute(() => window.requestFinished)); + } finally { + await mock.restore(); + } +}); +``` + +## См. также {/* #see-also */} + +- [browser.mock](../browser/mock.mdx) +- [clear](./clear.mdx) +- [restore](./restore.mdx) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/overview.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/overview.mdx index 6f2e4a36..a1c648a3 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/overview.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/overview.mdx @@ -2,48 +2,50 @@ sidebar_class_name: hidden --- -import Admonition from "@theme/Admonition"; +# Команды Testplane -# Команды testplane +## Обзор {/* #overview */} -## Обзор + - - Описаны только команды для последней версии Testplane v8 и WebDriverIO v9. Команды для более - старых версий стоит смотреть в документации WebDriverIO (пример для [WebDriverIO - v8][webdriverio@8-api]). - +Справочник описывает Testplane v9 и команды пакета `@testplane/webdriverio`. Перед запуском проверьте, какой протокол нужен команде: даже в одном браузере API WebDriver BiDi и Classic могут различаться. Для прежних версий используйте архив документации и [WebdriverIO v8](https://v8.webdriver.io/docs/api). -Так как в основе testplane лежит [WebDriverIO v9][webdriverio-api], то в ней доступны все команды, которые предоставляет WebDriverIO. +В Testplane нет неявных глобальных `browser`, `$` и `$$` из WDIO runner. Получайте `browser` из аргумента теста или через `this.browser` в обычной функции. Стрелочная функция не получает контекст `this` теста. Ищите элементы через `browser.$` и `browser.$$`. -Однако, описания команд на сайте [WebDriverIO][webdriverio-api] для 8-й версии не совсем подходят _as is_ для пользователей testplane из-за целого ряда причин: +## Пример {/* #examples */} -- в WebDriverIO объект `browser` существует в глобальном пространстве, тогда как в testplane нужно либо писать `this.browser`: +Оба теста открывают `/` относительно `baseUrl`. Тестовая страница должна содержать `h1` с текстом `Command examples`. - ```javascript - it("should test something", async () => { - await this.browser.url("https://testplane.io"); - // код теста... - }); - ``` +```javascript testplane=related-overview +const assert = require("node:assert/strict"); - либо получать объект `browser` из аргумента функции (обратите внимание, что объект `browser` передается внутри объекта!): +it("commands: use the browser fixture", async ({ browser }) => { + await browser.url("/"); + assert.equal(await browser.$("h1").getText(), "Command examples"); +}); - ```javascript - it("should test something", async ({ browser }) => { - await browser.url("https://testplane.io"); - // код теста... - }); - ``` +it("commands: use this.browser with a regular function", async function () { + await this.browser.url("/"); + assert.equal(await this.browser.$("h1").getText(), "Command examples"); +}); +``` -- аналогично функции `browser.$` и `browser.$$` в WebDriverIO доступны в тестах под именами `$` и `$$`, а в testplane к ним нужно обращаться по полному пути: `browser.$` и `browser.$$`; +## Как запустить примеры {/* #run-examples */} -- не проставлены связи между похожими командами: нет кластеризации команд; +Сохраните JavaScript-блок в файл теста Testplane. Для примеров с относительными URL укажите в `baseUrl` адрес локального HTTP-сервера. Настройте сервер так, чтобы он отдавал HTML-страницу по `/` и отвечал на запросы, описанные на странице команды. Запустите тест командой `npx testplane`. Для примера [downloadFile](./browser/downloadFile.mdx) также нужен Selenium Grid с поддержкой управляемых загрузок. -Тем не менее в наше описание пока ещё не вошли протоколо-специфичные команды. Соответствующие команды вы можете посмотреть на сайте WebDriverIO в разделе "[Protocols][webdriverio-protocols]". +## Выбор команды {/* #command-groups */} -Также в описаниях некоторых команд ссылки на отдельные рецепты все еще не локализованы и ведут на сайт WebDriverIO. +| Задача | Команды | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Подготовка и эмуляция страницы | [addInitScript](./browser/addInitScript.mdx), [emulate](./browser/emulate.mdx), [restore](./browser/restore.mdx), [setViewport](./browser/setViewport.mdx) | +| Собственные селекторы | [addLocatorStrategy](./browser/addLocatorStrategy.mdx), [browser.custom$](./browser/customDollar.mdx), [browser.custom$$](./browser/customDollarDollar.mdx), [element.custom$](./element/customDollar.mdx), [element.custom$$](./element/customDollarDollar.mdx) | +| Фреймы и загрузки | [switchFrame](./browser/switchFrame.mdx), [downloadFile](./browser/downloadFile.mdx) | +| Ограничение ресурсов | [throttleCPU](./browser/throttleCPU.mdx), [throttleNetwork](./browser/throttleNetwork.mdx) | +| Работа с элементом | [execute](./element/execute.mdx), [executeAsync](./element/executeAsync.mdx), [getElement](./element/getElement.mdx), [isStable](./element/isStable.mdx), [waitForStable](./element/waitForStable.mdx) | +| Перехват сети | [mock](./browser/mock.mdx), [waitForResponse](./mock/waitForResponse.mdx), [request](./mock/request.mdx), [requestOnce](./mock/requestOnce.mdx), [redirect](./mock/redirect.mdx), [redirectOnce](./mock/redirectOnce.mdx), [reset](./mock/reset.mdx) | +| Расширения Testplane | [extendOptions](./browser/extendOptions.mdx), [browser.unstable_captureDomSnapshot](./browser/unstable_captureDomSnapshot.mdx), [element.unstable_captureDomSnapshot](./element/unstable_captureDomSnapshot.mdx), [unstable_getCdp](./browser/unstable_getCdp.mdx) | -[webdriverio@8-api]: https://v8.webdriver.io/docs/api -[webdriverio-api]: https://webdriver.io/docs/api -[webdriverio-protocols]: https://webdriver.io/docs/api/webdriver +## Границы справочника {/* #scope */} + +Низкоуровневые команды WebDriver, BiDi и Appium не дублируются: см. [протоколы WebdriverIO](https://webdriver.io/docs/api/webdriver). Методы объектов `InitScript` и часов описаны на страницах [addInitScript](./browser/addInitScript.mdx) и [emulate](./browser/emulate.mdx), а не как отдельные команды браузера. Для внешних рецептов учитывайте различия версий и получения объекта `browser`. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-intercept-requests-and-responses.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-intercept-requests-and-responses.mdx index ee2e8ac7..193b0ec4 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-intercept-requests-and-responses.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-intercept-requests-and-responses.mdx @@ -7,15 +7,11 @@ import Admonition from "@theme/Admonition"; [//]: # "TODO: add screencasts" -Данный рецепт работает только при использовании _Chrome DevTools Protocol (CDP)_. - -Читайте подробности в разделе «[Как использовать CDP в Testplane][how-to-use-cdp]» +Примеры используют [Chrome DevTools Protocol (CDP)][how-to-use-cdp]. Для примеров с `browser.mock` нужна сессия **WebDriver Classic** с подключением к CDP. В BiDi-сессии [browser.mock](../commands/browser/mock.mdx) использует сетевые события BiDi: например, `respond(..., { fetchResponse: false })` не препятствует отправке запроса на сервер. -В CDP имеются домены [Fetch][fetch] и [Network][network], с помощью которых можно получить полный доступ ко всем сетевым запросам и ответам. При использовании Webdriver-протокола нам бы пришлось писать отдельный proxy-сервер и весь трафик направлять через него. - -В _webdriverio_ для работы с сетевыми запросами существует метод [mock][mock], который использует API домена [Fetch][fetch]. +В сессии Classic `browser.mock` перехватывает трафик через домен CDP [Fetch][fetch]. Домен [Network][network] предоставляет дополнительные сетевые события. С помощью этого метода мы можем: