メインコンテンツにスキップ

TypeScript

はじめに

Playwright は TypeScript をそのままサポートしています。テストを TypeScript で記述するだけで、Playwright はそれらを読み込み、JavaScript に変換して実行します。

Playwright は型チェックを行わず、重要ではない TypeScript コンパイルエラーがあってもテストを実行することに注意してください。Playwright と並行して TypeScript コンパイラを実行することをお勧めします。例えば GitHub Actions などで。

jobs:
test:
runs-on: ubuntu-latest
steps:
...
- name: Run type checks
run: npx tsc -p tsconfig.json --noEmit
- name: Run Playwright tests
run: npx playwright test

ローカル開発では、次のように watch モードで tsc を実行できます。

npx tsc -p tsconfig.json --noEmit -w

tsconfig.json

Playwright は、ロードする各ソースファイルに対して tsconfig.json を検出します。Playwright は以下の tsconfig オプションのみをサポートすることに注意してください: allowJsbaseUrlpathsreferences

テストの特定の環境設定を変更できるように、テストディレクトリに個別の tsconfig.json を設定することをお勧めします。以下はディレクトリ構造の例です。

src/
source.ts

tests/
tsconfig.json # test-specific tsconfig
example.spec.ts

tsconfig.json # generic tsconfig for all typescript sources

playwright.config.ts

tsconfig パス マッピング

Playwright は tsconfig.json で宣言された パス マッピング をサポートしています。baseUrl も設定されていることを確認してください。

以下は Playwright で動作する tsconfig.json の例です。

tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@myhelper/*": ["packages/myhelper/*"] // This mapping is relative to "baseUrl".
}
}
}

これで、マップされたパスを使用してインポートできます。

example.spec.ts
import { test, expect } from '@playwright/test';
import { username, password } from '@myhelper/credentials';

test('example', async ({ page }) => {
await page.getByLabel('User Name').fill(username);
await page.getByLabel('Password').fill(password);
});

tsconfig 解決

デフォルトでは、Playwright はディレクトリ構造を上位にたどり、tsconfig.json または jsconfig.json を探すことで、インポートされた各ファイルに最も近い tsconfig を検索します。この方法で、テスト専用に使用される tests/tsconfig.json ファイルを作成でき、Playwright はそれを自動的に検出します。

# Playwright will choose tsconfig automatically
npx playwright test

または、コマンドラインで単一の tsconfig ファイルを指定でき、Playwright はテストファイルだけでなく、インポートされたすべてのファイルにそれを使用します。

# Pass a specific tsconfig
npx playwright test --tsconfig=tsconfig.test.json

設定ファイルで単一の tsconfig ファイルを指定でき、それはテストファイル、レポーターなどのロードに使用されます。ただし、Playwright の設定自体やそこからインポートされたファイルはロード時には使用されません。

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
tsconfig: './tsconfig.test.json',
});

TypeScript でテストを手動でコンパイルする

TypeScript の実験的または最新の機能を使用している場合など、Playwright Test が TypeScript コードを正しく変換できない場合があります。これは通常 tsconfig.json で設定されます。

この場合、Playwright にテストを送信する前に、独自の TypeScript コンパイルを実行できます。

まず、テストディレクトリ内に tsconfig.json ファイルを追加します。

{
"compilerOptions": {
"target": "ESNext",
"module": "commonjs",
"moduleResolution": "Node",
"sourceMap": true,
"outDir": "../tests-out",
}
}

package.json に、2 つのスクリプトを追加します。

{
"scripts": {
"pretest": "tsc --incremental -p tests/tsconfig.json",
"test": "playwright test -c tests-out"
}
}

pretest スクリプトはテストで TypeScript を実行します。testtests-out ディレクトリに生成されたテストを実行します。-c 引数は、テストランナーが tests-out ディレクトリ内でテストを検索するように設定します。

その後、npm run test はテストをビルドして実行します。