Skip to content

Commit 82a10ce

Browse files
authored
docs: typescript-esm (#122)
1 parent 115c942 commit 82a10ce

2 files changed

Lines changed: 244 additions & 0 deletions

File tree

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# Typescript and ESM
2+
3+
## TypeScript in Testplane
4+
5+
Testplane supports TypeScript out of the box — you don’t need to set up additional tools for transpilation, you can start writing tests right away:
6+
7+
```typescript
8+
describe("test examples", () => {
9+
it("Open the main page and check the title", async ({ browser }) => {
10+
await browser.url("https://testplane.io/");
11+
12+
const title = await browser.getTitle();
13+
expect(title).toContain("Testplane");
14+
});
15+
});
16+
```
17+
18+
And you can specify `.ts` files directly in the config:
19+
20+
```typescript
21+
// .testplane.config.ts
22+
export default {
23+
sets: {
24+
desktop: {
25+
files: ["tests/**/*.ts"],
26+
},
27+
},
28+
};
29+
```
30+
31+
## Transpilation options
32+
33+
Testplane automatically uses `@swc/core` for transpilation if this package is installed in the project, otherwise, it uses `esbuild`, which is already included in Testplane.
34+
35+
:::warning Warning
36+
Type checking must be implemented separately using `tsc` and a config file.
37+
:::
38+
39+
If automatic transpilation doesn’t suit your project’s specifics, you can disable it using the `TS_ENABLE=false` environment variable and set it up manually.
40+
41+
To pass the required loader when setting it up manually, use the `--require option`, for example:
42+
43+
```bash
44+
-r ts-node/register
45+
```
46+
47+
## Working with import aliases
48+
49+
Many projects use path aliases in `tsconfig.json`:
50+
51+
```json
52+
{
53+
"compilerOptions": {
54+
"baseUrl": ".",
55+
"paths": {
56+
"@components/*": ["src/components/*"],
57+
"@utils/*": ["src/utils/*"],
58+
"@fixtures/*": ["tests/fixtures/*"]
59+
}
60+
}
61+
}
62+
```
63+
64+
However, the TypeScript compiler can resolve these paths only at compile time. At runtime, `Node.js` is unaware of these aliases, and you’ll get an error:
65+
66+
```bash
67+
Cannot find module '@components/Button'.
68+
```
69+
70+
#### Resolving paths at runtime
71+
72+
Install the `tsconfig-paths` package:
73+
74+
```bash
75+
npm install --save-dev tsconfig-paths
76+
```
77+
78+
Use the `--require` option:
79+
80+
```bash
81+
npx testplane -r tsconfig-paths/register
82+
```
83+
84+
For a more detailed introduction to `tsconfig-paths`, visit the [package documentation website](https://www.typescriptlang.org/tsconfig/#paths).
85+
86+
## Config typing
87+
88+
Testplane exports types for the configuration, for example:
89+
90+
```typescript
91+
import type { ConfigInput } from "testplane";
92+
93+
export default {
94+
// ...
95+
} satisfies ConfigInput;
96+
```
97+
98+
The `satisfies` operator checks whether a value is compatible with the specified type while preserving the original type of that value.
99+
100+
## Extending browser command types
101+
102+
Testplane supports custom commands with TypeScript:
103+
104+
```typescript
105+
import "webdriverio"; // Any import can be used here — it doesn’t have to be webdriverio
106+
107+
declare global {
108+
declare namespace WebdriverIO {
109+
interface Browser {
110+
customCommand: (arg: any) => Promise<void>;
111+
}
112+
}
113+
}
114+
```
115+
116+
You can read more about this in the [custom commands](https://testplane.io/docs/v8/basic-guides/custom-commands/) guide.
117+
118+
## Working with ESM
119+
120+
#### System limitations
121+
122+
To work with ESM, you’ll need `Node.js` version v22.0.0, v20.17.0, or higher. Interaction with `ECMAScript` is handled via the `require()` [function](https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require).
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# Typescript и ESM
2+
3+
## Typescript в Testplane
4+
5+
Testplane поддерживает TypeScript из коробки — вам не нужно настраивать дополнительные инструменты для транспайлинга, вы сразу можете писать тесты:
6+
7+
```typescript
8+
describe("test examples", () => {
9+
it("Открыть главную страницу и проверить заголовок", async ({ browser }) => {
10+
await browser.url("https://testplane.io/");
11+
12+
const title = await browser.getTitle();
13+
expect(title).toContain("Testplane");
14+
});
15+
});
16+
```
17+
18+
И указывать `.ts` файлы напрямую в конфиге:
19+
20+
```typescript
21+
// .testplane.config.ts
22+
export default {
23+
sets: {
24+
desktop: {
25+
files: ["tests/**/*.ts"],
26+
},
27+
},
28+
};
29+
```
30+
31+
## Варианты транспайлинга
32+
33+
Testplane автоматически использует `@swc/core` для транспайлинга, если этот пакет установлен в проекте, в противном случае он задействует `esbuild`, который уже включён в состав Testplane.
34+
35+
:::warning Важно
36+
Проверку типов необходимо реализовывать отдельно с помощью `tsc` и конфига.
37+
:::
38+
39+
Если автоматический трайнспайлинг не подходит из-за специфики проекта, вы можете отключить его с помощью переменной окружения `TS_ENABLE=false` и провести настройку самостоятельно.
40+
41+
Чтобы передать нужный лоадер при настройке вручную, используйте опцию `--require`, например:
42+
43+
```bash
44+
-r ts-node/register
45+
```
46+
47+
## Работа с алиасами в ипортах
48+
49+
Многие проекты используют алиасы путей в `tsconfig.json`:
50+
51+
```json
52+
{
53+
"compilerOptions": {
54+
"baseUrl": ".",
55+
"paths": {
56+
"@components/*": ["src/components/*"],
57+
"@utils/*": ["src/utils/*"],
58+
"@fixtures/*": ["tests/fixtures/*"]
59+
}
60+
}
61+
}
62+
```
63+
64+
Однако TypeScript-компилятор умеет резолвить эти пути только во время компиляции. В рантайме `Node.js` не знает об этих алиасах, и вы получите ошибку:
65+
66+
```bash
67+
Cannot find module '@components/Button'.
68+
```
69+
70+
#### Резолв путей в рантайме
71+
72+
Установите пакет `tsconfig-paths`:
73+
74+
```bash
75+
npm install --save-dev tsconfig-paths
76+
```
77+
78+
Ипользуйте опцию `--require`:
79+
80+
```bash
81+
npx testplane -r tsconfig-paths/register
82+
```
83+
84+
Для более подробного знакомства с `tsconfig-paths` перейдите на [сайт с документацией пакета](https://www.typescriptlang.org/tsconfig/#paths).
85+
86+
## Типизация конфига
87+
88+
Testplane экспортирует типы для конфигурации, например:
89+
90+
```typescript
91+
import type { ConfigInput } from "testplane";
92+
93+
export default {
94+
// ...
95+
} satisfies ConfigInput;
96+
```
97+
98+
Оператор `satisfies` проверяет совместимость значения с указанным типом при сохранении исходного типа этого значения.
99+
100+
## Расширение типов команд браузера
101+
102+
В Testplane имеется поддержка пользовательских команд с Typescript:
103+
104+
```typescript
105+
import "webdriverio"; // Может быть любой импорт, не обязательно webdriverio
106+
107+
declare global {
108+
declare namespace WebdriverIO {
109+
interface Browser {
110+
customCommand: (arg: any) => Promise<void>;
111+
}
112+
}
113+
}
114+
```
115+
116+
Подробнее об этом вы можете прочитать в статье про [кастомные команды](https://testplane.io/ru/docs/v8/basic-guides/custom-commands/).
117+
118+
## Работа с ESM
119+
120+
#### Системные ограничения
121+
122+
Для работы с ESM вам понадобится `Node.js` версии v22.0.0, v20.17.0 и выше. Взаимодействие с `ECMAScript` происходит с помощью [функции](https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require) `require()`.

0 commit comments

Comments
 (0)