ReviseAlgo Logo

Testing JavaScript

Unit Testing with Jest

Master unit testing with Jest. Learn matchers, lifecycle hooks, block organization, and command line options.

Last Updated: July 15, 2026 10 min read

1. Introduction

Jest is a popular JavaScript testing framework designed for simplicity and speed. It comes with built-in test runners, assertion matches, and mock helpers, requiring minimal configuration to get started.

2. Why It Matters

Writing clean, readable assertions requires a robust set of matching options (like asserting that objects match specific structures, checking if numbers are greater than values, or matching errors). Jest provides a comprehensive set of matchers to simplify these assertions.

3. Real-World Analogy

Think of a Quality Inspector Checklist:

  • Primitive Matcher (Is it yellow?): You check if the paint matches the design reference yellow color exactly (toBe reference equality).
  • Object Matcher (Does it contain the target features?): You check if the shipping crate contains the engine, wheels, and manual inside, ignoring their exact placement order (toEqual deep structural equality).

4. Jest Matchers

Jest provides different matchers depending on the type of data and comparison you want to perform:

5. Setup & Teardown Hooks

Jest provides lifecycles to set up test environments or clean up resources before and after test suites:

6. Practical Example

This script demonstrates a Jest test suite designed to validate a user profile creation helper:

7. Common Mistakes

  • Using toBe instead of toEqual for object assertions: toBe compares object references. Even if two objects have identical properties (e.g. { x: 1 } === { x: 1 } evaluates to false), toBe will fail. Use toEqual to check deep structural equality.

8. Quick Quiz

Q1: Which matcher should you use in Jest to verify that two object variables have the same values and properties?

A) toBe()

B) toEqual()

Answer: B — toEqual() performs deep structural equality checks on objects and arrays, verifying properties and values recursively.

9. Scenario-Based Challenge

The Product Inventory Validator:

An application tracks stock levels: [{ id: 1, qty: 10 }]. Design a Jest test suite using describe blocks and beforeEach to test adding items, removing items, and checking out inventory, ensuring the database state is reset before each test.

10. Debugging Exercise

Explain why this test fails to pass, and how to fix it:

test('validates user list matches output', () => {
  const users = ['Alice', 'Bob'];

// Bug: comparing array using toBe! expect(users).toBe(['Alice', 'Bob']); // Fails! Why? });

View Solution

Diagnosis: The test uses toBe to compare two array references. In JavaScript, arrays are objects, and comparing two different array instances with toBe checks for reference equality, which fails.

Fix: Use toEqual to check structural equality of the array elements:

test('validates user list matches output', () => {
  const users = ['Alice', 'Bob'];

expect(users).toEqual(['Alice', 'Bob']); // Passes! });

11. Interview Questions

🟢 Q1: Compare toBe and toEqual matchers in Jest and explain when to use each.

Answer:
toBe: Compares values using JavaScript's Object.is(). It checks for reference equality, verifying that values represent the same primitive or memory address.
When to use: For primitive values like numbers, strings, or booleans.
toEqual: Performs a deep comparison of properties and nested values. It checks for structural equality.
When to use: For complex objects, arrays, and map structures where you want to verify content instead of memory references.

12. Production Considerations

  • Isolated Tests: Ensure all unit tests are isolated. Never rely on global states mutated by sibling tests, and clear database or state variables inside beforeEach hooks to prevent leaks across tests.