TypeScript
簡介
Playwright 支援開箱即用的 TypeScript。您只需用 TypeScript 編寫測試,Playwright 就會讀取它們,轉換為 JavaScript 並執行。
請注意,即使存在非嚴重的 TypeScript 編譯錯誤,Playwright 也不會檢查類型並會執行測試。我們建議您在 Playwright 旁邊執行 TypeScript 編譯器。例如在 GitHub 動作上
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 程式碼,例如當您使用實驗性或非常新的 TypeScript 功能時,這些功能通常在 tsconfig.json
中設定。
在這種情況下,您可以在將測試發送到 Playwright 之前執行自己的 TypeScript 編譯。
首先在 tests 目錄內新增一個 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
將建置測試並執行它們。