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
ローカル開発では、tsc
を ウォッチモードで次のように実行できます。
npx tsc -p tsconfig.json --noEmit -w
tsconfig.json
Playwright は、ロードする各ソースファイルに対して tsconfig.json
を検出します。Playwright は以下の tsconfig オプションのみを**サポートします**:allowJs
、baseUrl
、paths
、references
。
テスト専用に設定を変更できるように、テストディレクトリ内に別の 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
の例を以下に示します。
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@myhelper/*": ["packages/myhelper/*"] // This mapping is relative to "baseUrl".
}
}
}
これで、マッピングされたパスを使用してインポートできます。
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 の設定ファイル自体やそこからインポートされたファイルのロード時には使用されません。
import { defineConfig } from '@playwright/test';
export default defineConfig({
tsconfig: './tsconfig.test.json',
});
TypeScript でテストを手動でコンパイルする
Playwright Test が TypeScript コードを正しく変換できない場合があります。例えば、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 を実行します。test
は tests-out
ディレクトリに生成されたテストを実行します。-c
引数は、テストランナーが tests-out
ディレクトリ内でテストを探すように設定します。
その後、npm run test
はテストをビルドして実行します。