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)?
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