gutenbergdocs/docs/contributors/code/e2e/migration.md
2025-10-22 01:40:18 +08:00

37 lines
3.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 迁移指南
本文档概述了将 Jest + Puppeteer 测试迁移至 Playwright 的典型流程。请注意,迁移过程也是重构或重写部分测试的良好契机。开始迁移前,请先阅读[最佳实践](https://github.com/WordPress/gutenberg/tree/HEAD/docs/contributors/code/e2e/README.md#best-practices)指南。
## 测试迁移步骤
1.`packages/e2e-tests/specs` 中选择要迁移的测试套件,将 `.test.js` 重命名为 `.spec.js`,并置于 `test/e2e/specs` 内的相同文件夹结构中。
2.`@wordpress/e2e-test-utils-playwright` 引入测试辅助工具:
```js
const { test, expect } = require( '@wordpress/e2e-test-utils-playwright' );
```
3. 将所有出现的 `describe`、`beforeAll`、`beforeEach`、`afterEach` 和 `afterAll` 加上 `test.` 前缀。例如,`describe` 变为 `test.describe`
4. 使用[夹具 API](https://playwright.dev/docs/test-fixtures) 引入之前全局的变量,如 `page``browser`
5. 删除所有对 `e2e-test-utils` 的导入。改为使用夹具 API 直接获取 `admin`、`editor`、`pageUtils` 和 `requestUtils`。(注意:`admin`、`editor` 和 `pageUtils` 不能在 `beforeAll``afterAll` 中使用,需改用 `requestUtils` 重写。)
6. 如果缺少某个工具函数,且步骤较少,可尝试直接在测试中内联实现操作。如果认为有必要作为测试工具函数实现,请参考以下[指南](#测试工具函数迁移步骤)。
7. 根据推荐的[最佳实践](https://github.com/WordPress/gutenberg/tree/HEAD/docs/contributors/code/e2e/README.md#best-practices)手动迁移测试中的其他细节。请注意,尽管 Playwright 和 Puppeteer 的 API 差异较小,但仍需进行一些手动调整。
## 测试工具函数迁移步骤
在迁移测试工具函数前请仔细考虑是否必要。Playwright 提供了许多易读且强大的 API使得许多工具函数不再需要。可先尝试在测试中直接内联实现相同功能。仅当此方法不适用时再参考以下指南。适合在 `e2e-test-utils-playwright` 包中实现的工具函数示例包括复杂的浏览器 API`pageUtils.dragFiles``pageUtils.pressKeys`)以及状态设置 API`requestUtils.*`)。
<div class="callout callout-info">
<code>e2e-test-utils-playwright</code> 包并非旨在完全替代 Jest + Puppeteer 的 <code>e2e-test-utils</code> 包。部分工具函数仅为简化迁移过程而创建,并非必需。
</div>
Playwright 工具函数的组织方式与 `e2e-test-utils` 包略有不同。`e2e-test-utils-playwright` 包将工具函数分为以下文件夹:
- `admin` - 与 WordPress 后台或 WordPress 后台用户界面相关的工具函数(例如 `visitAdminPage`)。
- `editor` - 用于块编辑器的工具函数(例如 `clickBlockToolbarButton`)。
- `pageUtils` - 用于与浏览器交互的通用工具函数(例如 `pressKeys`)。
- `requestUtils` - 用于发起 REST API 请求的工具函数(例如 `activatePlugin`)。这些工具函数用于测试的初始化和清理。
1. 复制 `e2e-test-utils` 中的现有文件,根据工具函数类型粘贴到 `e2e-test-utils-playwright``admin`、`editor`、`page` 或 `request` 文件夹中。
2. 更新工具函数中需要重写的部分:
- `page``browser` 变量在 `admin`、`editor` 和 `pageUtils` 中可通过 `this.page``this.browser` 访问。
- 同一类中的所有其他工具函数可通过 `this` 访问,并绑定到同一实例。可移除所有 `import` 语句,改用 `this` 访问。
- 如果熟悉 TypeScript可考虑将工具函数更新为 TypeScript 版本。
3. 在 `index.ts` 中导入新迁移的工具函数,并将其作为实例字段放入 `Admin`/`Editor`/`PageUtils`/`RequestUtils` 类中。