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.
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.
Share Improve this question edited Mar 24, 2020 at 12:33 skyboyer 23.8k7 gold badges62 silver badges71 bronze badges asked Mar 24, 2020 at 11:49 Eduardo H.Eduardo H. 451 gold badge2 silver badges9 bronze badges 2- 4 Two different objects will never pare as equal. It's not a problem with property ordering. – Pointy Commented Mar 24, 2020 at 11:51
- 1 Does this answer your question? Loose match one value in jest.toHaveBeenCalledWith – segFault Commented Mar 24, 2020 at 12:05
2 Answers
Reset to default 5You 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.