TypeScript
Playwright Test 开箱即用地支持 TypeScript。您只需用 TypeScript 编写测试,Playwright Test 将读取它们,转换为 JavaScript 并运行。这适用于 CommonJS 模块和 ECMAScript 模块。
TypeScript 与 CommonJS
Node.js 默认使用 CommonJS 模块。除非您使用 '.mjs' 或 '.mts' 扩展名,或在 package.json 中指定 type: "module",否则 Playwright Test 将把所有 TypeScript 文件视为 CommonJS。然后您可以像往常一样导入而无需扩展名。
考虑这个用 TypeScript 编写的辅助模块:
// helper.ts
export const username = 'John';
export const password = 'secret';
您可以像往常一样从辅助模块导入:
// example.spec.ts
import { test, expect } from '@playwright/test';
import { username, password } from './helper';
test('example', async ({ page }) => {
await page.getByLabel('User Name').fill(username);
await page.getByLabel('Password').fill(password);
});
TypeScript 与 ESM
您可以通过在 package.json 文件中设置 type: "module" 来选择使用 ECMAScript 模块。Playwright Test 一旦读取 playwright.config.ts 文件就会切换到 ESM 模式,因此请确保您有一个。
Playwright Test 遵循 TypeScript 中对 ESM 的实验性支持,并且根据规范,从模块导入时需要扩展名,可以是 '.js' 或 '.ts'。
首先,在您的 package.json 中启用模块:
{
"name": "my-package",
"version": "1.0.0",
"type": "module",
}
然后像往常一样用 TypeScript 编写辅助模块:
// helper.ts
export const username = 'John';
export const password = 'secret';
从模块导入时指定扩展名:
// example.spec.ts
import { test, expect } from '@playwright/test';
import { username, password } from './helper.ts';
test('example', async ({ page }) => {
await page.getByLabel('User Name').fill(username);
await page.getByLabel('Password').fill(password);
});
TypeScript 与 ESM 需要 Node.js 16 或更高版本。
tsconfig.json
Playwright 将为它加载的每个源文件选择 tsconfig.json。请注意,Playwright 仅支持以下 tsconfig 选项:paths 和 baseUrl。
我们建议在测试目录中设置单独的 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 Test 配合使用的示例 tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".", // 如果指定了 "paths",则必须指定此项。
"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);
});
使用 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 将构建测试并运行它们。