【问题标题】:In jest, how do I use "toHaveBeenCalledWith" and only match part of an object in an array argument?开玩笑,我如何使用“toHaveBeenCalledWith”并且只匹配数组参数中对象的一部分?
【发布时间】:2021-08-28 19:34:27
【问题描述】:

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

expect(myMockFn).toHaveBeenCalledWith(arrayArgument);

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

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

实际调用是使用看起来像这样的参数进行的

[{x: 2, y: 3, id: 'some-guid'}]

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

【问题讨论】:

  • 能否提供完整的测试用例?
  • 你事先知道数组的元素个数吗?你还知道每个对象的属性吗?

标签: jestjs mocking ts-jest


【解决方案1】:

您可以结合使用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. toHaveBeenCalledWithexpect.arrayContaining 调用,它验证它是否用数组调用
  2. expect.arrayContaining 有一个数组。该数组有一个带有objectContaining 的对象,该对象与该对象进行部分匹配。

【讨论】:

  • 我喜欢你的回答。如果使用对象数组调用模拟函数,它是否适用? (具有多个对象项的数组)
  • 它应该可以工作@SubratoPatnaik,因为这是一个arrayContaining。它正在测试数组是否有至少一个对象与指定的两个键值对部分匹配。如果我们想匹配更多的元素,我们可以添加它。有许多可能的组合。
  • 你能举一个例子来解释你的答案吗?这会很有帮助。
  • @SubratoPatnaik,对不起,我很困惑。你说的是哪一个?一个例子?
猜你喜欢
  • 1970-01-01
  • 2020-07-04
  • 2019-11-08
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 2014-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多