Skip to main content

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.jsonjsconfig.json 來找到最接近的 tsconfig。這樣,您可以建立只用於測試的 tests/tsconfig.json 檔案,Playwright 會自動選擇它。

# Playwright 會自動選擇 tsconfig
npx playwright test

或者,您可以在命令列中指定單一 tsconfig 檔案,Playwright 會將其用於所有匯入的檔案,而不僅僅是測試檔案。

# 傳遞特定的 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

有時,Playwright Test 無法正確轉換您的 TypeScript 程式碼,例如當您使用實驗性或最新的 TypeScript 功能時,通常在 tsconfig.json 中組態設定。

在這種情況下,您可以在將測試傳送到 Playwright 之前執行自己的 TypeScript 編譯。

首先在測試目錄內新增 tsconfig.json 檔案:

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

package.json 中,新增兩個腳本:

{
"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 將建置測試並執行它們。