26

I'm using Typescript and Jest. In Jest, if I want to check if my function was called I can run

expect(myMockFn).toHaveBeenCalledWith(arrayArgument);

I want to check if my function was called with an array argument that contains an object with some values. For example,

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

The actual call is made with a parameter that looks like

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

so my expect is failing because I don't have the id attribute in the first object of the array, but I would like to match and ignore the ID, since it will be different each time, even though the other arguments are the same. How do I construct such an expect call with Jest?

pynexj
  • 19,215
  • 5
  • 38
  • 56
Dave
  • 15,639
  • 133
  • 442
  • 830

1 Answers1

52

You can use a combination of arrayContaining and objectContaining to make this work.

Reference:

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

Here is some sample code for you:

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
            })
        ])
    );
});

Sample output:

$ 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.

Here is some explanation:

  1. toHaveBeenCalledWith is called with expect.arrayContaining which verifies if it was called with an array
  2. expect.arrayContaining has an array. The array has an object with objectContaining which does the partial match against the object.
ahuemmer
  • 1,653
  • 9
  • 22
  • 29
manishg
  • 9,520
  • 1
  • 16
  • 19
  • I liked your answer. Does it work with if mock function is called with an array of objects? (array with multiple object items) – Subrato Pattanaik Jun 14 '21 at 12:33
  • It should work @SubratoPatnaik as this is a `arrayContaining`. It is testing if the array has an at least one object with partial match to two key value pairs as specified. If we want to match more elements, we can add that. There are many combinations possible. – manishg Jun 14 '21 at 12:52
  • Could you give one example about explaining this in your answer? It would be helpful. – Subrato Pattanaik Jun 14 '21 at 13:08
  • @SubratoPatnaik, sorry I am confused. Which one are you talking about? An example of? – manishg Jun 14 '21 at 20:04