【问题标题】:Custom failure message for Jest testJest 测试的自定义失败消息
【发布时间】:2021-05-19 18:42:15
【问题描述】:

我正在测试一个带有部分随机输入的函数。无论如何,随机化的输入对象片段应该可以工作,但是如果我碰巧遇到一个失败的案例,我想通过在我的失败消息中包含无效输入来了解它是什么。

如何让 Jest 显示超出 expect 内容的失败消息?

这是我的代码:

    describe("my module", () => {
      it("should pass with some randomized inputs", () => {
        const partialRandomInput = {
          name: "Hardcoded",
          age: Math.random() * 100,
          yearsOfExperience: Math.random() * 30
        };
        const actualOutput = myModule(partialRandomInput);

        expect(actualOutput).toEqual(false); // If this fails I only see the expect comparison that happened, which may not be helpful
      });
    });

也许在我上面的代码中,唯一的失败是如果随机 age 小于 5 并且随机 yearsOfExperience 小于 10。我想看看这些值当我的测试失败时用于partialRandomInput

【问题讨论】:

    标签: jestjs


    【解决方案1】:

    不要使用随机输入进行测试。

    即使代码打算与随机数一起使用,您也应该使用预定义的值对其进行测试,以确保其结果一致。通过使用随机数,您无法确保使用的输入将覆盖实现中的相同“分支”。

    您可以尝试使用一组预定义的值和预期结果

    describe.each([
      [10, 10, true],
      [22, 10, false],
      [35, 11, true],
      [50, 3, false],
      [60, 7, false],
    ])(
      "with age: %p and yearsOfExperience: %p",
      (age, yearsOfExperience, expected) => {
        it(`should return: ${expected}`, () => {
          expect(
            myModule({
              name: "Hardcoded",
              age,
              yearsOfExperience,
            })
          ).toEqual(expected);
        });
      }
    );
    
    

    但是为了回答这个问题 - 您可以在执行测试之前生成随机数,然后您可以:

    1. Extend expect
    2. 在测试描述中添加值
    describe.each(
      Array.from(new Array(10), () => [Math.random() * 100, Math.random() * 10])
    )("with age: %p and yearsOfExperience: %p", (age, yearsOfExperience) => {
      test(`returns false`, () => {
        expect(
          myModule({
            name: "Hardcoded",
            age,
            yearsOfExperience,
          })
        ).toBe(false);
      });
    });
    

    【讨论】:

    • 太好了,这对解释我的问题的直接答案和指出更好的方法都非常有帮助。
    猜你喜欢
    • 2014-10-19
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2018-02-26
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多