1

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.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Eduardo H.
  • 25
  • 1
  • 2
  • 8
  • 4
    Two different objects will never compare as equal. It's not a problem with property ordering. – Pointy Mar 24 '20 at 11:51
  • 1
    Does this answer your question? [Loose match one value in jest.toHaveBeenCalledWith](https://stackoverflow.com/questions/52337116/loose-match-one-value-in-jest-tohavebeencalledwith) – segFault Mar 24 '20 at 12:05

2 Answers2

4

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

segFault
  • 3,887
  • 1
  • 19
  • 31
0
  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.

skyboyer
  • 22,209
  • 7
  • 57
  • 64