简体   繁体   中英

Jest function toHaveBeenCalledWith to ignore object order

Im testing with what arguments a function was called but its not passing because the order of properties inside an object, like:

const obj = {
  name: 'Bla',
  infos: {
    info1: '1',
    info2: '2'
  }
}

expect(function).toHaveBeenCalledWith(obj)

The error says that was called like this: { name: 'bla', infos: {info2: '2', info1: '1'} }

I changed orders but didn't work.

You could follow a similar approach to this SO answer .

Example:

// Assuming some mock setup like this...
const mockFuncton = jest.fn();

const expectedObj = {
  name: 'Bla',
  infos: {
    info1: '1',
    info2: '2'
  }
}

// Perform operation(s) being tested...

// Expect the function to have been called at least once
expect(mockFuncton).toHaveBeenCalled();

// Get the 1st argument from the mock function call
const functionArg = mockFuncton.mock.calls[0][0];

// Expect that argument matches the expected object
expect(functionArg).toMatchObject(expectedObj);

// Comparison using toEqual() instead which might be a better approach for your usecase
expect(functionArg).toEqual(expectedObj);

Expect.toMatchObject() Docs

Expect.toEqual() Docs

  it('does not care on properties ordering', () => {
    const a = jest.fn();
    a({ a: 1, b: 2, c: {d1: 1, d2: 2} });
    expect(a).toHaveBeenCalledWith({c: {d2: 2, d1: 1}, b: 2, a: 1});
  });

passes for me with Jest 24.9.0

Under the hood , Jest applies "isEqual" check, not referential check

But we cannot check for functions equality this way. Also partial matching will need custom matcher.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM