如何在Playwright中记录信息并使其显示在Trace Viewer中(效果类似test.step)
如何在Playwright中记录信息并使其显示在Trace Viewer中(效果类似test.step)
嘿,我刚好知道怎么解决这个问题!其实Playwright有几个实用的办法能让自定义日志信息出现在Trace Viewer里,不用局限于test.step的标题内容:
使用
test.info().annotations添加注释
这种方式会把自定义信息附加到对应步骤的详情中,在Trace Viewer的「Annotations」区域展示,非常适合和当前测试步骤绑定的说明:await test.step("Navigate to the blog home page and confirm it is loaded.", async () => { test.info().annotations.push({ type: "info", description: "some piece of information I want you to see in the trace viewer." }); // 你的测试逻辑代码 });你可以自定义
type字段,比如用"warning"、"error"来区分不同类型的日志,让Trace Viewer里的信息更清晰。用迷你空步骤承载日志
如果希望日志像test.step一样在步骤树里直观展示,可以创建一个没有业务逻辑的空step,把日志内容作为step标题:await test.step("Navigate to the blog home page and confirm it is loaded.", async () => { await test.step("Log: some piece of information I want you to see in the trace viewer.", async () => {}); // 你的测试逻辑代码 });这种方式的好处是日志和测试步骤层级对应,查看Trace时能快速定位到日志产生的环节。
使用
test.info().log()记录统一日志
如果你想把自定义日志和Playwright的内置日志放在一起管理,可以用这个方法,日志会出现在Trace Viewer的「Logs」标签页中:await test.step("Navigate to the blog home page and confirm it is loaded.", async () => { test.info().log("info", "some piece of information I want you to see in the trace viewer."); // 你的测试逻辑代码 });第一个参数是日志级别(支持"info"、"warning"、"error"等),第二个参数是具体的日志内容,方便后续筛选不同级别的日志。
这些方法在官方文档里确实不算特别显眼,但亲测都能在Trace Viewer里正常显示,你可以根据自己的需求选最合适的方式~
备注:内容来源于stack exchange,提问作者WayneRoseberry
相关产品推荐
相关产品推荐

