Course contentsShow
← JavaScript
Lesson 2673 of 2,72354. Testing in JavaScriptFree lesson

Basic Equality Assertions

Using toBe and toEqual to check primitive values and object equality.

Basic Equality Assertions

In this lesson, you'll learn how to use toBe and toEqual to verify that values match your expectations in tests.

After defining your test structure with describe and it blocks, assertions are how you actually check that your code works correctly. The two most fundamental assertion methods for equality are toBe and toEqual, and knowing when to use each is essential.

Understanding toBe

toBe checks strict equality using JavaScript's === operator. It's perfect for primitive values like numbers, strings, booleans, null, and undefined:

// Using toBe for primitives
it('should calculate correct sum', () => {
  const result = 2 + 2;
  expect(result).toBe(4);
});

it('should return correct string', () => {
  const greeting = 'Hello';
  expect(greeting).toBe('Hello');
});

Think of toBe as asking: "Are these the exact same thing?"

Understanding toEqual

toEqual performs a deep equality check. Use it for objects and arrays, where you care about the contents, not whether they're the same reference in memory:

// Using toEqual for objects and arrays
it('should create correct user object', () => {
  const user = { name: 'Alice', age: 30 };
  expect(user).toEqual({ name: 'Alice', age: 30 });
});

it('should return correct array', () => {
  const numbers = [1, 2, 3];
  expect(numbers).toEqual([1, 2, 3]);
});

If you used toBe with objects, it would fail even if the contents match, because they're different object references.

Key Takeaway: Use toBe for primitive values and strict identity checks; use toEqual for comparing the contents of objects and arrays.