.toEqual(value)
Use .toEqual
to compare recursively all properties of object instances (also known as "deep" equality). It calls Object.is
to compare primitive values, which is even better for testing than ===
strict equality operator.
For example, .toEqual
and .toBe
behave differently in this test suite, so all the tests pass:
const can1 = {
flavor: 'grapefruit',
ounces: 12,
};
const can2 = {
flavor: 'grapefruit',
ounces: 12,
};
describe('the La Croix cans on my desk', () => {
test('have all the same properties', () => {
expect(can1).toEqual(can2);
});
test('are not the exact same can', () => {
expect(can1).not.toBe(can2);
});
});
Note:.toEqual
won't perform a deep equality check for two errors. Only themessage
property of an Error is considered for equality. It is recommended to use the.toThrow
matcher for testing against errors.
If differences between properties do not help you to understand why a test fails, especially if the report is large, then you might move the comparison into the expect
function. For example, use equals
method of Buffer
class to assert whether or not buffers contain the same content:
- rewrite
expect(received).toEqual(expected)
asexpect(received.equals(expected)).toBe(true)
- rewrite
expect(received).not.toEqual(expected)
asexpect(received.equals(expected)).toBe(false)