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

Strict vs Loose Equality in Tests

How toBe uses === while toEqual performs deep equality checks.

Strict vs Loose Equality in Tests

What you'll learn: How test assertion methods differ in their equality comparisons, specifically when they use strict versus deep equality.

The Two Flavors of Equality

When writing assertions, you need to understand that JavaScript test runners offer different methods for comparing values, and they don't all work the same way.

toBe() uses strict equality (===). This means it checks if two values are the exact same thing in memory. It works perfectly for primitives like numbers, strings, and booleans, but for objects and arrays, it only passes if both sides reference the identical object instance.

toEqual() performs a deep equality check. This means it looks inside objects and arrays, comparing their contents property-by-property and element-by-element, even if they're different instances in memory.

The Practical Difference

Think of toBe() like checking if two people are literally the same person (identical twins won't pass this test). Think of toEqual() like checking if two people are wearing identical outfits (different people, same appearance).

// This passes - same primitive value
expect(5).toBe(5);

// This FAILS - different object instances
expect({ name: "Alice" }).toBe({ name: "Alice" });

// This PASSES - same contents, different instances
expect({ name: "Alice" }).toEqual({ name: "Alice" });

// This FAILS - toBe checks reference equality
const user = { name: "Bob" };
expect(user).toBe({ name: "Bob" });

// This PASSES - same reference
expect(user).toBe(user);

Key Takeaway: Use toBe() for primitives and reference checks; use toEqual() when you care about the contents of objects or arrays, not whether they're the same instance in memory.