首页 > 解决方案 > 有关失败测试的更多信息?

问题描述

如何获取有关失败测试的更多信息?理想情况下,我希望在 except 函数上有第二个参数,我可以在其中传递将显示在控制台上的字符串。就像是:

var i = 0;
var j = 0;
expect( i / j, `failed when dividing ${i} ${j}` )

我也试过这个:

test.describe("Test description", () => {
    test("Test name", async ({ page }) => {
        ...snip...
        await test.step("Testing DIV0 is fail", async () => {
            await expect(4/0).toBe(5);
        });
       ...snip...
    });
});

Testing DIV0 is fail命令行可能会在1/1000 秒内快速闪烁文本。这没有帮助。如果我找不到我想要发现的问题,基本上 Playwright 是无法使用的。

我所看到的:


  1) myTests.spec.ts:40:2 › Test description 

    Error: expect(received).toBe(expected) // Object.is equality

    Expected: 5
    Received: Infinity

      44 |              await test.step("Testing DIV0 is fail", async () => {
    > 45 |                      await expect(4/0).toBe(5);
         |                                        ^
      46 |              });


        at myTests.spec.ts:45:22
        at TestTypeImpl._step (...\node_modules\@playwright\test\lib\test\testType.js:213:13)
        at Function.step (...\node_modules\@playwright\test\lib\test\transform.js:133:12)
        at ...\tests\myTests.spec.ts:44:14
        at WorkerRunner._runTestWithBeforeHooks (...\node_modules\@playwright\test\lib\test\workerRunner.js:450:7)

  Slow test: basicPageChecks.spec.ts (24s)

  1 failed
    myTests.spec.ts:40:2 › Test description 
  12 skipped

我可以很容易地在代码中添加注释。或添加日志记录。

也许这些额外的数据可以在报告中获得??我错过了什么吗?

标签: playwright

解决方案


从这个答案中大量借用:在 NodeJS 中重新抛出异常并且不丢失堆栈跟踪

一个很好的解决方案(意味着只记录错误,它不需要使用附加的 if 语句仔细检查每个逻辑步骤,并且不会使用 try/catch 包装每个例外将代码行数增加三倍)是下列的:

添加一个新类

export class RethrownError extends Error {
    constructor(message, error) {
        super(message);
        this.name = this.constructor.name;
        if (!error) {
            throw new Error("RethrownError requires a message and error");
        } else {
            this.original_error = error;
            this.stack_before_rethrow = this.stack;
            const message_lines =  (this.message.match(/\n/g)||[]).length + 1;
            this.stack = this.stack.split("\n").slice(0, message_lines+1).join("\n") + "\n" + error.stack;
        }
    }
    static expectWithMessage(message, cb) {
        try {
            cb()
        } catch(ex) {
            throw new RethrownError(message, ex);
        }
    }
}

更改除外

await expect(4/0).toBe(5);

await RethrownError.expectWithMessage("DIV by zero", () => {expect(4/0).toBe(5); });

这个解决方案的问题是期望线非常难看(线长)。

希望有一天 MS 会更新expect()以接受第二个错误消息参数。


推荐阅读