Skip to content

Commit 1b7448b

Browse files
committed
docs: add custom commands guide
1 parent 672d138 commit 1b7448b

File tree

7 files changed

+284
-116
lines changed

7 files changed

+284
-116
lines changed

docs/config/_partials/examples/_prepare-browser-add-browser-command.mdx

Lines changed: 0 additions & 25 deletions
This file was deleted.

docs/config/_partials/examples/_prepare-browser-overwrite-command.mdx

Lines changed: 0 additions & 22 deletions
This file was deleted.

docs/config/prepare-browser.mdx

Lines changed: 25 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
import Admonition from "@theme/Admonition";
2-
import AddBrowserCommandExample from "@site/docs/config/_partials/examples/_prepare-browser-add-browser-command.mdx";
3-
import AddElementCommandExample from "@site/docs/config/_partials/examples/_prepare-browser-add-element-command.mdx";
4-
import OverwriteCommandExample from "@site/docs/config/_partials/examples/_prepare-browser-overwrite-command.mdx";
52
import AddMultipleCommandsExample from "@site/docs/config/_partials/examples/_prepare-browser-add-multiple-commands.mdx";
63

74
# prepareBrowser
@@ -10,44 +7,37 @@ import AddMultipleCommandsExample from "@site/docs/config/_partials/examples/_pr
107

118
This parameter is a hook. The function specified for this parameter will be automatically called before running tests in the browser. The function receives a reference to the browser session as an argument.
129

13-
Typically, new commands are added to the browser or the behavior of existing commands is extended within this function.
10+
The `prepareBrowser` hook is a perfect place to set up all of your custom commands or overwrite existing ones.
1411

15-
## Usage Examples {#example}
16-
17-
### Example 1: Adding a new command to the browser {#example_add_new_command_to_browser}
18-
19-
To add a new command, use the [browser.addCommand()][add-command] function.
20-
21-
<AddBrowserCommandExample />
22-
23-
### Example 2: Adding a new command to an element {#example_2_add_new_command_to_element}
24-
25-
You can add a command not to the browser, but to an element. In this case, the third argument of the [browser.addCommand()][add-command] function should be set to `true`.
26-
27-
<Admonition type="warning">
28-
If a command is added to an element, not to the browser, the function is executed in the context
29-
of the element!
12+
<Admonition type="info">
13+
Read more about custom commands in [our guide](../guides/custom-commands.mdx).
3014
</Admonition>
3115

32-
<AddElementCommandExample />
33-
34-
Inside the function, the commands [getLocation()][get-location] and [getSize()][get-size], which are available for the element, are used.
35-
36-
After adding the `getCoords()` command, it can be used in tests as follows:
16+
## Usage Examples {#example}
3717

38-
```typescript
39-
const { left, top, right, bottom } = await browser.$(".selector").getCoords();
18+
### Adding new browser commands or overwriting existing browser commands
19+
20+
This is how you can add or overwrite browser commands:
21+
22+
```typescript title="testplane.config.ts"
23+
import type { ConfigInput } from "testplane";
24+
import { openScenario, customUrl } from "./testplane/browser-commands";
25+
import { getCoords } from "./testplane/element-commands";
26+
27+
export default {
28+
// ...
29+
prepareBrowser: function (browser) {
30+
// Browser commands
31+
browser.addCommand("openScenario", openScenario);
32+
// Element commands
33+
browser.addCommand("getCoords", getCoords, true);
34+
// Browser command overwrites
35+
browser.overwriteCommand("url", customUrl);
36+
},
37+
} satisfies ConfigInput;
4038
```
4139

42-
### Example 3: Overwriting an existing command {#example_3_overwrite_command}
43-
44-
To change an existing command, use the [browser.overwriteCommand()][overwrite-command] command.
45-
46-
For example, we might want to pass an object with query parameters as a separate argument to the [browser.url()][url] command:
47-
48-
<OverwriteCommandExample />
49-
50-
### Example 4: Adding a set of commands from a folder {#example_4_add_commands_from_folder}
40+
### Adding a set of commands from a folder
5141

5242
If the project has many specific commands, it is convenient to store them in a separate folder, and add all commands at once in a unified manner in `prepareBrowser`. For example:
5343

docs/guides/custom-commands.mdx

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
import Tabs from "@theme/Tabs";
2+
import TabItem from "@theme/TabItem";
3+
import Admonition from "@theme/Admonition";
4+
import AddElementCommandExample from "@site/docs/config/_partials/examples/_prepare-browser-add-element-command.mdx";
5+
6+
# Custom Commands
7+
8+
Testplane allows you to enhance your test suites by adding custom commands. These commands can streamline repetitive tasks, encapsulate complex actions, and improve code readability.
9+
10+
<Admonition title="What you'll learn">
11+
12+
- How to add custom commands to the browser object.
13+
- How to add custom commands to elements.
14+
- Ways to overwrite existing commands.
15+
- Make custom commands work in a TypeScript environment.
16+
17+
</Admonition>
18+
19+
## Adding Custom Commands to the Browser Object
20+
21+
<Admonition type="tip">
22+
A good place to add all of your custom commands is
23+
[`prepareBrowser`](../config/prepare-browser.mdx) hook.
24+
</Admonition>
25+
26+
To add a custom command to the `browser` object, use the `addCommand` method. Here's how you can define a command that retrieves both the URL and title of the current page:
27+
28+
```typescript
29+
browser.addCommand("getUrlAndTitle", async function () {
30+
return {
31+
url: await this.getUrl(),
32+
title: await this.getTitle(),
33+
};
34+
});
35+
```
36+
37+
You can then use this custom command in your tests:
38+
39+
```typescript
40+
it("should fetch URL and title", async function () {
41+
const result = await browser.getUrlAndTitle();
42+
console.log(result); // { url: 'https://example.com', title: 'Example Domain' }
43+
});
44+
```
45+
46+
## Adding Custom Commands to Elements
47+
48+
Custom commands can also be added to element instances. For instance, to create a command that gets element position:
49+
50+
<AddElementCommandExample />
51+
52+
Note the last, third parameter is set to `true` — it means that this command should be added to element instances.
53+
54+
## Overwriting Existing Commands
55+
56+
There might be scenarios where you need to modify the behavior of existing commands. Testplane allows you to overwrite these commands using the `overwriteCommand` method. For example, to add logging to the `click` command:
57+
58+
```typescript
59+
browser.overwriteCommand("click", async function (this: WebdriverIO.Element, origClick, options) {
60+
console.log("Element clicked:", this.selector);
61+
await origClick(options);
62+
});
63+
```
64+
65+
In this example, before executing the original `click` function, a message is logged to the console.
66+
67+
## Using Custom Commands with TypeScript
68+
69+
To ensure TypeScript recognizes your custom commands, you need to augment the WebdriverIO types. To do that, follow these simple steps:
70+
71+
1. Create a `custom-commands.d.ts` file in your project.
72+
73+
2. Make sure TypeScript compiler "sees" this file during build: you might need to include it in your `tsconfig.json`.
74+
75+
3. Write your type definitions as follows. Note that there are two file contexts in TypeScript: module and ambient. If you have at least one import/export in your file, the file is in "module" mode, otherwise it's in ambient. Choose declaration style accordingly.
76+
77+
<Tabs>
78+
<TabItem value="module" label="Module mode" default>
79+
80+
```typescript
81+
import 'webdriverio'; // Can be any import, not necessarily webdriverio
82+
83+
declare global {
84+
declare namespace WebdriverIO {
85+
interface Browser {
86+
customCommand: (arg: any) => Promise<void>
87+
}
88+
89+
interface Element {
90+
elementCustomCommand: (arg: any) => Promise<void>
91+
}
92+
}
93+
}
94+
```
95+
96+
</TabItem>
97+
<TabItem value="ambient" label="Ambient mode">
98+
99+
```typescript
100+
declare namespace WebdriverIO {
101+
interface Browser {
102+
customCommand: (arg: any) => Promise<void>
103+
}
104+
105+
interface Element {
106+
elementCustomCommand: (arg: any) => Promise<void>
107+
}
108+
}
109+
```
110+
111+
</TabItem>
112+
113+
</Tabs>
114+
115+
This declaration extends the `Browser` and `Element` interfaces to include your custom commands, allowing TypeScript to recognize them without errors.

i18n/ru/docusaurus-plugin-content-docs/current/config/prepare-browser.mdx

Lines changed: 24 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
import Admonition from "@theme/Admonition";
2-
import AddBrowserCommandExample from "@site/docs/config/_partials/examples/_prepare-browser-add-browser-command.mdx";
3-
import AddElementCommandExample from "@site/docs/config/_partials/examples/_prepare-browser-add-element-command.mdx";
4-
import OverwriteCommandExample from "@site/docs/config/_partials/examples/_prepare-browser-overwrite-command.mdx";
52
import AddMultipleCommandsExample from "@site/docs/config/_partials/examples/_prepare-browser-add-multiple-commands.mdx";
63

74
# prepareBrowser
@@ -12,42 +9,35 @@ import AddMultipleCommandsExample from "@site/docs/config/_partials/examples/_pr
129

1310
Обычно внутри данной функции к браузеру добавляют новые команды, или расширяют поведение уже существующих команд.
1411

15-
## Примеры использования {#example}
16-
17-
### Пример 1: добавляем новую команду для браузера {#example_add_new_command_to_browser}
18-
19-
Для добавления новой команды воспользуемся функцией [browser.addCommand()][add-command].
20-
21-
<AddBrowserCommandExample />
22-
23-
### Пример 2: добавляем новую команду для элемента {#example_2_add_new_command_to_element}
24-
25-
Можно добавить команду не для браузера, а для элемента. Тогда третьим аргументом функции [browser.addCommand()][add-command] надо указать `true`.
26-
27-
<Admonition type="warning">
28-
Если добавляется команда для элемента, а не для браузера, то функция выполняется в контексте
29-
элемента!
12+
<Admonition type="info">
13+
Узнайте больше о кастомных командах в [нашем рецепте](../guides/custom-commands.mdx).
3014
</Admonition>
3115

32-
<AddElementCommandExample />
33-
34-
Внутри функции применяются команды [getLocation()][get-location] и [getSize()][get-size], которые доступны для элемента.
35-
36-
После добавления команды `getCoords()`, её можно использовать в тестах следующим образом:
16+
## Примеры использования {#example}
3717

38-
```typescript
39-
const { left, top, right, bottom } = await browser.$(‘.selector’).getCoords();
18+
### Добавление новых команд и перезапись существующих команд браузера
19+
20+
Так вы можете добавлять и перезаписывать браузерные команды:
21+
22+
```typescript title="testplane.config.ts"
23+
import type { ConfigInput } from "testplane";
24+
import { openScenario, customUrl } from "./testplane/browser-commands";
25+
import { getCoords } from "./testplane/element-commands";
26+
27+
export default {
28+
// ...
29+
prepareBrowser: function (browser) {
30+
// Browser commands
31+
browser.addCommand("openScenario", openScenario);
32+
// Element commands
33+
browser.addCommand("getCoords", getCoords, true);
34+
// Browser command overwrites
35+
browser.overwriteCommand("url", customUrl);
36+
},
37+
} satisfies ConfigInput;
4038
```
4139

42-
### Пример 3: меняем уже существующую команду {#example_3_overwrite_command}
43-
44-
Чтобы изменить уже существующую команду, воспользуемся командой [browser.overwriteCommand()][overwrite-command].
45-
46-
Например, мы можем захотеть передавать в команду [browser.url()][url] отдельным аргументом объект с query-параметрами:
47-
48-
<OverwriteCommandExample />
49-
50-
### Пример 4: добавляем набор команд из папки {#example_4_add_commands_from_folder}
40+
### Добавление набора команд из папки
5141

5242
Если в проекте много своих специфических команд, то их удобно хранить в отдельной папке, а в `prepareBrowser` добавлять все команды сразу унифицированным образом. Например:
5343

0 commit comments

Comments
 (0)