You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 09:44:30