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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 122 additions & 0 deletions docs/basic-guides/typescript-esm.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Typescript and ESM

## TypeScript in Testplane

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:

```typescript
describe("test examples", () => {
it("Open the main page and check the title", async ({ browser }) => {
await browser.url("https://testplane.io/");

const title = await browser.getTitle();
expect(title).toContain("Testplane");
});
});
```

And you can specify `.ts` files directly in the config:

```typescript
// .testplane.config.ts
export default {
sets: {
desktop: {
files: ["tests/**/*.ts"],
},
},
};
```

## Transpilation options

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.

:::warning Warning
Type checking must be implemented separately using `tsc` and a config file.
:::

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.

To pass the required loader when setting it up manually, use the `--require option`, for example:

```bash
-r ts-node/register
```

## Working with import aliases

Many projects use path aliases in `tsconfig.json`:

```json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components/*": ["src/components/*"],
"@utils/*": ["src/utils/*"],
"@fixtures/*": ["tests/fixtures/*"]
}
}
}
```

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:

```bash
Cannot find module '@components/Button'.
```

#### Resolving paths at runtime

Install the `tsconfig-paths` package:

```bash
npm install --save-dev tsconfig-paths
```

Use the `--require` option:

```bash
npx testplane -r tsconfig-paths/register
```

For a more detailed introduction to `tsconfig-paths`, visit the [package documentation website](https://www.typescriptlang.org/tsconfig/#paths).

## Config typing

Testplane exports types for the configuration, for example:

```typescript
import type { ConfigInput } from "testplane";

export default {
// ...
} satisfies ConfigInput;
```

The `satisfies` operator checks whether a value is compatible with the specified type while preserving the original type of that value.

## Extending browser command types

Testplane supports custom commands with TypeScript:

```typescript
import "webdriverio"; // Any import can be used here — it doesn’t have to be webdriverio

declare global {
declare namespace WebdriverIO {
interface Browser {
customCommand: (arg: any) => Promise<void>;
}
}
}
```

You can read more about this in the [custom commands](https://testplane.io/docs/v8/basic-guides/custom-commands/) guide.

## Working with ESM

#### System limitations

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).
Comment thread
Nikolaengel marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# Typescript и ESM

## Typescript в Testplane

Testplane поддерживает TypeScript из коробки — вам не нужно настраивать дополнительные инструменты для транспайлинга, вы сразу можете писать тесты:

```typescript
describe("test examples", () => {
it("Открыть главную страницу и проверить заголовок", async ({ browser }) => {
await browser.url("https://testplane.io/");

const title = await browser.getTitle();
expect(title).toContain("Testplane");
});
});
```

И указывать `.ts` файлы напрямую в конфиге:

```typescript
// .testplane.config.ts
export default {
sets: {
desktop: {
files: ["tests/**/*.ts"],
},
},
};
```

## Варианты транспайлинга

Testplane автоматически использует `@swc/core` для транспайлинга, если этот пакет установлен в проекте, в противном случае он задействует `esbuild`, который уже включён в состав Testplane.

:::warning Важно
Проверку типов необходимо реализовывать отдельно с помощью `tsc` и конфига.
:::

Если автоматический трайнспайлинг не подходит из-за специфики проекта, вы можете отключить его с помощью переменной окружения `TS_ENABLE=false` и провести настройку самостоятельно.

Чтобы передать нужный лоадер при настройке вручную, используйте опцию `--require`, например:

```bash
-r ts-node/register
```

## Работа с алиасами в ипортах

Многие проекты используют алиасы путей в `tsconfig.json`:

```json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components/*": ["src/components/*"],
"@utils/*": ["src/utils/*"],
"@fixtures/*": ["tests/fixtures/*"]
}
}
}
```

Однако TypeScript-компилятор умеет резолвить эти пути только во время компиляции. В рантайме `Node.js` не знает об этих алиасах, и вы получите ошибку:

```bash
Cannot find module '@components/Button'.
```

#### Резолв путей в рантайме
Comment thread
Nikolaengel marked this conversation as resolved.

Установите пакет `tsconfig-paths`:

```bash
npm install --save-dev tsconfig-paths
```

Ипользуйте опцию `--require`:

```bash
npx testplane -r tsconfig-paths/register
```

Для более подробного знакомства с `tsconfig-paths` перейдите на [сайт с документацией пакета](https://www.typescriptlang.org/tsconfig/#paths).

## Типизация конфига

Testplane экспортирует типы для конфигурации, например:

```typescript
import type { ConfigInput } from "testplane";

export default {
// ...
} satisfies ConfigInput;
```

Оператор `satisfies` проверяет совместимость значения с указанным типом при сохранении исходного типа этого значения.

## Расширение типов команд браузера

В Testplane имеется поддержка пользовательских команд с Typescript:

```typescript
import "webdriverio"; // Может быть любой импорт, не обязательно webdriverio

declare global {
declare namespace WebdriverIO {
interface Browser {
customCommand: (arg: any) => Promise<void>;
}
}
}
```

Подробнее об этом вы можете прочитать в статье про [кастомные команды](https://testplane.io/ru/docs/v8/basic-guides/custom-commands/).

## Работа с ESM

#### Системные ограничения

Для работы с ESM вам понадобится `Node.js` версии v22.0.0, v20.17.0 и выше. Взаимодействие с `ECMAScript` происходит с помощью [функции](https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require) `require()`.
Loading