What is the difference between 'toBe' and 'toEqual' in Jest?

sshh picture sshh · Jul 19, 2017 · Viewed 33.6k times · Source

Jest documentation reads:

toBe just checks that a value is what you expect. It uses === to check strict equality.

And for toEqual:

Use .toEqual when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity—this is also known as "deep equal". For example, toEqual and toBe behave differently in this test suite, so all the tests pass.

const x = { a: { b: 3 } };
const y = { a: { b: 3 } };

expect(x).toEqual(y);
expect(x).toBe(y);

In this case, toEqual passes but toBe fails. I understand that toEqual passes because it does a deep equal check. Why is toBe failing in this case?

Also, are there best practices for using toBe and toEqual (not just in Jest but in other testing frameworks, too)?

Answer

Andreas Köberle picture Andreas Köberle · Jul 20, 2017

It fails cause x and y are different instances and not equal as in (x === y) === false. You can use toBe for primitives like strings, numbers or booleans for everything else use toEqual. For example

x = 4 
y = 4
x === y // true

x = 'someString'
y = 'someString'
x === y // true

Even empty objects are not equal

x = {}
y = {}
x === y //false