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 オプションのみをサポートしていることに注意してください: 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 コードを正しく変換できないことがあります。たとえば、tsconfig.json
で通常構成される TypeScript の実験的またはごく最近の機能を使用している場合などです。
この場合、テストを Playwright に送信する前に、独自の TypeScript コンパイルを実行できます。
まず、tsconfig.json
ファイルを tests ディレクトリ内に追加します
{
"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
はテストをビルドして実行します。