Jest - 测试失败时将参数传递给测试内部调用的函数

Jest - log parameters passed into a function called inside the test when test failed

我有一个 Jest 测试描述为:

it('Full name must be >= 3 letters', () => {
    ['', 'a', 'ab', 'a ', 'a    ', '     a'].forEach((fullName) => {
      expect(() => userBuilder.build({ fullName })).toThrowError();
    });
  });

当任何迭代失败时,测试失败并指向 expect 行:

user › Full name must be >= 3 letters

    expect(received).toThrowError()

    Received function did not throw

      15 |     ['', 'a', 'ab', 'a ', 'a    ', '     a', 'asdf'].forEach((fullName) => {
      16 |       console.debug('testing', fullName);
    > 17 |       expect(() => userBuilder.build({ fullName })).toThrowError();
         |                                                     ^
      18 |     });
      19 |   });
      20 |

      at src/api/user/user.test.ts:17:53
          at Array.forEach (<anonymous>)
      at Object.<anonymous> (src/api/user/user.test.ts:15:54)

这不是很有帮助,因为它在循环中。我需要知道在 expect 失败时的迭代中作为 fullName 传递了哪些参数。

开始,我知道我可以使用
test.each([...])('Full name must be >= 3 letters, testing: %s'){...
但是这里每次迭代都被认为是一个单独的测试,我在几十个不同的测试中有数百次这样的迭代(全名必须 <= 50 个字符,全名必须只包含字母和空格,等等)。这不必要地使我的测试套件膨胀,一遍又一遍地打印重复的 Full name must be >= 3 letters, testing: 文本。

我知道我可以 console.debug('testing', fullName) 每次迭代,但它会记录每次迭代的输出,并在每个输出周围添加一些详细信息,并且不会打印失败消息,因此需要进行多次测试,很难弄清楚哪个迭代在哪个测试中失败了。我不知道如何仅在期望失败时记录输出。

对于测试运行者来说,这似乎是一件很简单的事情,我敢肯定我一定在这里遗漏了一些东西。

不确定它是否重要,但我正在使用 ts-jest 作为打字稿。

使用describe to group the validation rules, then use test.each或forEach进行测试。

describe('Full name must be >= 3 letters', () => {
  ['', 'a', 'ab', 'a ', 'a    ', '     a'].forEach((fullName) => {
    it(`should throw error when full name is "${fullName}"`, () => {
      expect(() => userBuilder.build({ fullName })).toThrowError();
    });
  });
});

然后,失败消息将如下所示:

  Full name must be >= 3 letters
    ✓ should throw error when full name is "" (9 ms)
    ✓ should throw error when full name is "a" (1 ms)
    ✕ should throw error when full name is "ab" (1 ms)
    ✓ should throw error when full name is "a " (1 ms)
    ✓ should throw error when full name is "a    "
    ✓ should throw error when full name is "     a"

  ● Full name must be >= 3 letters › should throw error when full name is "ab"

    expect(received).toThrowError()

    Received function did not throw

      10 |   ['', 'a', 'ab', 'a ', 'a    ', '     a'].forEach((fullName) => {
      11 |     it(`should throw error when full name is "${fullName}"`, () => {
    > 12 |       expect(() => userBuilder.build({ fullName })).toThrowError();
         |                                                     ^
      13 |     });
      14 |   });
      15 | });