.toBe(value)

Use .toBe to compare primitive values or to check referential identity of object instances. It calls Object.is to compare values, which is even better for testing than === strict equality operator.

For example, this code will validate some properties of the can object:

  1. const can = {
  2. name: 'pamplemousse',
  3. ounces: 12,
  4. };
  5. describe('the can', () => {
  6. test('has 12 ounces', () => {
  7. expect(can.ounces).toBe(12);
  8. });
  9. test('has a sophisticated name', () => {
  10. expect(can.name).toBe('pamplemousse');
  11. });
  12. });

Don't use .toBe with floating-point numbers. For example, due to rounding, in JavaScript 0.2 + 0.1 is not strictly equal to 0.3. If you have floating point numbers, try .toBeCloseTo instead.

Although the .toBe matcher checks referential identity, it reports a deep comparison of values if the assertion fails. 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, to assert whether or not elements are the same instance:

  • rewrite expect(received).toBe(expected) as expect(Object.is(received, expected)).toBe(true)
  • rewrite expect(received).not.toBe(expected) as expect(Object.is(received, expected)).toBe(false)