Tracing
用于收集和保存 Playwright 追踪记录的 API。Playwright 追踪记录可以在脚本运行后通过 Trace Viewer 查看。
您可能更倾向于在配置文件中启用追踪功能,而不是直接使用 context.tracing
。
context.tracing
API 会捕获浏览器操作和网络活动,但不会记录测试断言(如 expect
调用)。我们推荐通过 Playwright Test 配置启用追踪功能,这样可以包含断言信息并提供更完整的追踪记录用于调试测试失败。
在执行操作前开始记录追踪。最后停止追踪并保存到文件。
const browser = await chromium.launch();
const context = await browser.newContext();
await context.tracing.start({ screenshots: true, snapshots: true });
const page = await context.newPage();
await page.goto('https://playwright.dev');
expect(page.url()).toBe('https://playwright.dev');
await context.tracing.stop({ path: 'trace.zip' });
方法
group
Added in: v1.49请优先使用 test.step
替代此方法。
在追踪记录中创建一个新分组,将后续所有 API 调用归入该分组,直到调用 tracing.groupEnd() 为止。分组可以嵌套,并会在追踪查看器中显示。
用法
// 使用 test.step 替代
await test.step('登录', async () => {
// ...
});
参数
-
在追踪查看器中显示的分组名称。
-
options
Object (可选)
返回值
groupEnd
Added in: v1.49关闭由 tracing.group() 创建的最后一个分组。
用法
await tracing.groupEnd();
返回值
start
添加于: v1.12开始记录追踪信息。
我们建议您在配置文件中启用追踪功能,而不是直接使用 Tracing.start
。
context.tracing
API 会捕获浏览器操作和网络活动,但不会记录测试断言(如 expect
调用)。我们推荐通过 Playwright Test 配置启用追踪功能,这样可以包含断言信息并提供更完整的追踪记录用于调试测试失败。
用法
await context.tracing.start({ screenshots: true, snapshots: true });
const page = await context.newPage();
await page.goto('https://playwright.dev');
expect(page.url()).toBe('https://playwright.dev');
await context.tracing.stop({ path: 'trace.zip' });
参数
options
Object (可选)-
如果指定,中间追踪文件将以给定名称前缀保存在 browserType.launch() 中指定的 tracesDir 目录下。要指定最终的追踪 zip 文件名,需要向 tracing.stop() 传递
path
参数。 -
是否在追踪过程中捕获屏幕截图。截图用于构建时间线预览。
-
如果设为 true,追踪将:
- 捕获每次操作的 DOM 快照
- 记录网络活动
-
sources
boolean (可选) 添加于: v1.17#是否包含追踪操作的源文件。
-
在 Trace Viewer 中显示的追踪名称。
-
返回值
startChunk
新增于: v1.15开始一个新的追踪块。如果需要在同一个 BrowserContext 上记录多个追踪,可以先调用 tracing.start() 一次,然后通过 tracing.startChunk() 和 tracing.stopChunk() 创建多个追踪块。
用法
await context.tracing.start({ screenshots: true, snapshots: true });
const page = await context.newPage();
await page.goto('https://playwright.dev');
await context.tracing.startChunk();
await page.getByText('Get Started').click();
// startChunk 和 stopChunk 之间的所有操作都会被记录在追踪中
await context.tracing.stopChunk({ path: 'trace1.zip' });
await context.tracing.startChunk();
await page.goto('http://example.com');
// 保存包含不同操作的第二个追踪文件
await context.tracing.stopChunk({ path: 'trace2.zip' });
参数
options
Object (可选)-
如果指定,中间追踪文件将会以给定名称前缀保存在 browserType.launch() 中指定的 tracesDir 目录下。要指定最终的追踪 zip 文件名,需要将
path
参数传递给 tracing.stopChunk()。 -
在 Trace Viewer 中显示的追踪名称。
-
返回值
stop
Added in: v1.12停止追踪。
用法
await tracing.stop();
await tracing.stop(options);
参数
返回值
stopChunk
Added in: v1.15停止当前追踪块。关于多个追踪块的详细信息,请参阅 tracing.startChunk()。
用法
await tracing.stopChunk();
await tracing.stopChunk(options);
参数
options
Object (可选)-
将自上次 tracing.startChunk() 调用以来收集的追踪记录导出到指定路径的文件中。
-
返回值