开个玩笑,我如何使用 "toHaveBeenCalledWith" 并仅匹配数组参数中的对象的一部分?

In jest, how do I use "toHaveBeenCalledWith" and only match part of an object in an array argument?

我正在使用 Typescript 和 Jest。在 Jest 中,如果我想检查我的函数是否被调用,我可以 运行

expect(myMockFn).toHaveBeenCalledWith(arrayArgument);

我想检查我的函数是否使用包含具有某些值的对象的数组参数调用。例如,

expect(myMockFn).toHaveBeenCalledWith( [{x: 2, y: 3}] );

实际调用是用一个看起来像

的参数进行的
[{x: 2, y: 3, id: 'some-guid'}]

所以我的期望失败了,因为我在数组的第一个对象中没有 id 属性,但我想匹配并忽略 ID,因为它每次都会不同,即使另一个论点是一样的。如何用 Jest 构建这样的 expect 调用?

您可以结合使用 arrayContainingobjectContaining 来完成这项工作。

参考:

  1. https://jestjs.io/docs/expect#expectarraycontainingarray
  2. https://jestjs.io/docs/expect#expectobjectcontainingobject

这里有一些示例代码供您参考:

function something(a, b, somefn) {
    somefn([{
        x: a,
        y: b,
        id: 'some-guid'
    }]);
}
test('Testing something', () => {
    const mockSomeFn = jest.fn();
    something(2, 3, mockSomeFn);
    expect(mockSomeFn).toHaveBeenCalledWith(
        expect.arrayContaining([
            expect.objectContaining({
                x: 2,
                y: 3
            })
        ])
    );
});

示例输出:

$ jest
 PASS  ./something.test.js
  ✓ Testing something (3 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.257 s, estimated 1 s
Ran all test suites.
✨  Done in 0.84s.

这里有一些解释:

  1. toHaveBeenCalledWith 是用 expect.arrayContaining 调用的,它验证它是否是用数组
  2. 调用的
  3. expect.arrayContaining 有一个数组。该数组有一个带有 objectContaining 的对象,该对象对对象进行部分匹配。