跳到主要内容

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

我们建议在 tests 目录中设置单独的 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 配置本身或从中导入的任何文件时使用。

playwright.config.ts
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 将构建测试并运行它们。