Search code examples
jestjsmockingts-jest

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


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?


Solution

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