跳至主要内容

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 will choose tsconfig automatically
npx playwright test

或者,您可以在命令行中指定一个单独的tsconfig文件来使用,Playwright将把它用于所有导入的文件,而不仅仅是测试文件。

# Pass a specific tsconfig
npx playwright test --tsconfig=tsconfig.test.json

您可以在配置文件中指定一个单独的tsconfig文件,该文件将用于加载测试文件、报告器等。但是,在加载playwright配置本身或从其中导入的任何文件时不会使用该tsconfig文件。

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 会构建测试并运行它们。