跳到主要内容

TypeScript 支持

简介

Playwright 原生支持 TypeScript。您可以直接用 TypeScript 编写测试,Playwright 会读取这些测试文件,将其转换为 JavaScript 并运行。

请注意,Playwright 不会检查类型,即使存在非关键性的 TypeScript 编译错误也会运行测试。我们建议您在运行 Playwright 的同时运行 TypeScript 编译器。例如在 GitHub Actions 中:

jobs:
test:
runs-on: ubuntu-latest
steps:
...
- name: 运行类型检查
run: npx tsc -p tsconfig.json --noEmit
- name: 运行 Playwright 测试
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 # 测试专用的 tsconfig
example.spec.ts

tsconfig.json # 适用于所有 TypeScript 源的通用 tsconfig

playwright.config.ts

tsconfig 路径映射

Playwright 支持在 tsconfig.json 中声明的路径映射。请确保同时设置了 baseUrl

以下是一个适用于 Playwright 的 tsconfig.json 示例:

tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@myhelper/*": ["packages/myhelper/*"] // 此映射相对于 "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 将会构建测试并执行它们。