What's The Difference Between toEqual And toMatchObject In Jest
toEqual and toMatchObject are assertions in Jest. When you write tests, the general idea is to check if something matches your expectation or not.
toEqual
is like deep equality, it helps you to compare recursively all the properties of object instances. It checks to make sure that the expected object is exactly the same as the received object.
For example:
The test below would fail because both the received and expected objects aren't identical.
test('matcher', () => {
const received = {
a: 1,
b: 2
};
const expected = {
a: 1,
};
expect(received).toEqual(expected)
});
// this fails because both received and expected aren't identical
On the other hand:
toMatchObject
checks that an object matches a subset of the properties of another object. The word subset is very important cos that's what distinguishes toEqual
and toMatchObject
.
If a part of an object exists in another object, using toMatchObject
would pass, but if it were with toEqual
like the example above, it would fail.
test('matcher', () => {
const received = {
a: 1,
b: 2
};
const expected = {
a: 1,
};
expect(received).toMatchObject(expected)
});
// this passes because the expected object is a subset of the received object
Be careful to use the correct assertion for your tests.
I learned about this distinction because I had previously used toMatchObject
and expected an error to occur when the received object deviates slightly from the expected object. For that scenario, it was better to use toEqual
and now I know.