Unit Testing with Jest

Unit testing verifies individual pieces of code (units) work as expected. Jest is a popular JavaScript testing framework focused on simplicity and support for modern JS features.

Illustration of Unit Testing with Jest
Illustration of Unit Testing with Jest

💡 Why Jest?

Jest requires minimal configuration, supports snapshots, mocks, and runs tests in parallel for speed.

Basic Jest Test Structure

Tests are organized in test or it blocks with descriptive names, containing assertions to validate code behavior.

📌 Deep Dive: Simple Test Example

JAVASCRIPT
test('adds 1 + 2 to equal 3', () => {
  expect(1 + 2).toBe(3);
});
Output
Test passes if 1 + 2 equals 3

Key Jest Functions

  • test(name, fn): Defines a test case.
  • describe(name, fn): Groups related tests.
  • expect(value): Creates an assertion object.
  • toBe(value): Checks strict equality.
  • toEqual(value): Checks deep equality (objects/arrays).
  • beforeEach(fn) / afterEach(fn): Setup/teardown hooks.

Testing Functions with Jest

Write tests that call your function and assert expected results.

📌 Deep Dive: Function Testing

JAVASCRIPT
function sum(a, b) {
  return a + b;
}

test('sum adds two numbers', () => {
  expect(sum(2, 3)).toBe(5);
});
Output
Test passes if sum(2, 3) returns 5

Mock Functions

Jest can replace dependencies with mock functions to isolate testing and track calls.

📌 Deep Dive: Simple Mock Example

JAVASCRIPT
const mockCallback = jest.fn();

[1, 2, 3].forEach(mockCallback);

test('mock function called 3 times', () => {
  expect(mockCallback.mock.calls.length).toBe(3);
});
Output
Test passes if mockCallback called 3 times

⚠️ Test Isolation

Avoid sharing state between tests; use beforeEach or reset mocks to ensure independence.

Test File Naming and Running Tests

  • Test files end with .test.js or .spec.js.
  • Run tests via jest CLI or npm test if configured.
  • Watch mode reruns tests on file changes for fast feedback.
Common Jest Matchers
MatcherPurpose
toBe(value)Strict equality (===)
toEqual(value)Value equality (objects/arrays)
toBeTruthy()Boolean true-like values
toBeFalsy()Boolean false-like values
toContain(item)Array or string contains
toHaveBeenCalled()Mock function called

💡 Tip

Write small, focused tests that verify one piece of functionality clearly and independently.