| **Name** | **Type** | **Description** |
| script | String or Function | The script to be executed. |
| arguments | Any | Arguments for the script. The last argument must be a callback function, which will be called once the script has been executed. |
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. | -
| **Name** | **Type** | **Description** |
| url | String | The URL of the request to mock. |
| method | String or Function | The HTTP method to filter the resource. |
| headers | Object or Function | The request headers to filter the resource. |
| responseHeaders | Object or Function | The response headers to filter the resource. |
| postData | String or Function | The request postData to filter the resource. |
| statusCode | Number or Function | The status code to filter the resource. |
| **Name** | **Type** | **Description** |
| offline | Boolean | Enable emulation of a loss of connection. |
| latency | Number | Minimum latency from the sent request to received response headers, in milliseconds. |
| downloadThroughput | Number | Maximum total download throughput (bytes/sec). _-1_ disables download throttling. |
| uploadThroughput | Number | Maximum total upload throughput (bytes/sec). _-1_ disables upload throttling. |
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| **Name** | **Type** | **Description** |
| url | String | The URL to open. |
Outside
First
Second
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 */} + +`PromiseOutside
'; + }); + 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| **Name** | **Type** | **Description** |
| errorCode | ErrorCode | The response error code. Possible values are listed [above](#overview). |
| **Name** | **Type** | **Description** |
| errorCode | ErrorCode | The response error code. Possible values are listed [above](#overview). |
| **Name** | **Type** | **Description** |
| overwrites | MockOverwrite | _Payload_ to overwrite the response. |
| header | Object | Overwrite specific headers. |
| statusCode | Number | Overwrite the response status code. |
| fetchResponse | Boolean | Fetch the actual response before replying with fake data. |
| **Name** | **Type** | **Description** |
| overwrites | MockOverwrite | _Payload_ to overwrite the response. |
| header | Object | Overwrite specific headers. |
| statusCode | Number | Overwrite the response status code. |
| fetchResponse | Boolean | Fetch the actual response before replying with fake data. |
| **Имя** | **Тип** | **Описание** |
| script | String или Function | Скрипт, который необходимо выполнить. |
| arguments | Any | Аргументы для скрипта. Последним аргументом должна быть колбэк-функция, которая будет вызвана после того, как скрипт будет выполнен. |
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` | -`-` | -Путь к файлу с состоянием. | -
| **Имя** | **Тип** | **Описание** |
| url | String | URL, запрос которого нужно имитировать. |
| method | String или Function | http-метод, по которому нужно фильтровать ресурс. |
| headers | Object или Function | Заголовки запроса, по которым нужно фильтровать ресурс. |
| responseHeaders | Object или Function | Заголовки ответа, по которым нужно фильтровать ресурс. |
| postData | String или Function | postData запроса, по которому нужно фильтровать ресурс. |
| statusCode | Number или Function | Код статуса, по которому нужно фильтровать ресурс. |
| **Имя** | **Тип** | **Описание** |
| offline | Boolean | Включить эмуляцию потери соединения. |
| latency | Number | Минимальная задержка от отправленного запроса до полученных заголовков ответа, в миллисекундах. |
| downloadThroughput | Number | Максимальная совокупная пропускная способность загрузки (байт/сек). _-1_ отключает регулирование загрузки. |
| uploadThroughput | Number | Максимальная совокупная пропускная способность аплоада (байт/сек). _-1_ отключает регулирование аплоада. |
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| **Имя** | **Тип** | **Описание** |
| url | String | URL, который надо открыть. |
Outside
First
Second
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 */} + +`PromiseOutside
'; + }); + 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| **Имя** | **Тип** | **Описание** |
| errorCode | ErrorCode | Код ошибки ответа. Возможные значения см. [выше](#overview). |
| **Имя** | **Тип** | **Описание** |
| errorCode | ErrorCode | Код ошибки ответа. Возможные значения см. [выше](#overview). |
| **Имя** | **Тип** | **Описание** |
| overwrites | MockOverwrite | _Payload_ для перезаписи ответа. |
| header | Object | Перезаписать определенные заголовки. |
| statusCode | Number | Перезаписать код состояния ответа. |
| fetchResponse | Boolean | Получить реальный ответ, прежде чем отвечать с помощью поддельных данных. |
| **Имя** | **Тип** | **Описание** |
| overwrites | MockOverwrite | _Payload_ для перезаписи ответа. |
| header | Object | Перезаписать определенные заголовки. |
| statusCode | Number | Перезаписать код состояния ответа. |
| fetchResponse | Boolean | Получить реальный ответ, прежде чем отвечать с помощью поддельных данных. |