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
。这样,您可以在 tests/tsconfig.json
中创建一个仅用于测试的 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 测试可能无法正确转换您的 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
,它将编译测试并运行它们。