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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)