.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:

  1. const can1 = {
  2. flavor: 'grapefruit',
  3. ounces: 12,
  4. };
  5. const can2 = {
  6. flavor: 'grapefruit',
  7. ounces: 12,
  8. };
  9. describe('the La Croix cans on my desk', () => {
  10. test('have all the same properties', () => {
  11. expect(can1).toEqual(can2);
  12. });
  13. test('are not the exact same can', () => {
  14. expect(can1).not.toBe(can2);
  15. });
  16. });
Note: .toEqual won't perform a deep equality check for two errors. Only the message 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) as expect(received.equals(expected)).toBe(true)
  • rewrite expect(received).not.toEqual(expected) as expect(received.equals(expected)).toBe(false)