Next.js Course
Next.js
/
Intermediate

Jest

Definition

A popular JavaScript Testing Framework that provides the test runner, assertion library, and mocking capabilities needed to write Unit Tests.

Explain Like I'm New

You wrote a function `calculateTax(amount)`. You don't want to manually type numbers into your app to see if it works. Jest runs a script that automatically feeds 50 different numbers into your function and asserts that the math comes out perfectly every time.

Real World Example

Testing utility functions, API route handlers, or complex Redux/Zustand state logic independently from the React UI.

Common Use Cases

  • •Unit testing
  • •TDD (Test-Driven Development)

Interactive Example

// utils/math.ts
export const calculateTax = (amount) => amount * 0.10;

// __tests__/math.test.ts
import { calculateTax } from '../utils/math';

// 1. Describe the test suite
describe('Math Utilities', () => {
  
  // 2. Define an individual test
  it('should correctly calculate a 10% tax', () => {
    
    // 3. Execution & Assertion
    const result = calculateTax(100);
    expect(result).toBe(10);
  });

  it('should return 0 when amount is 0', () => {
    expect(calculateTax(0)).toBe(0);
  });
});

Interview Questions

basic

  • Is Jest primarily used for Unit Testing or End-to-End (E2E) testing?

intermediate

  • What is 'Mocking' in Jest, and why is it necessary?

Flash Cards

Question

Which testing?

Click to reveal answer
Answer

Unit Testing. (Testing isolated functions or individual components without running a real browser).

Question

What is Mocking?

Click to reveal answer
Answer

Mocking is replacing a real function (like a database call) with a fake one. In a unit test, you don't want to actually hit your production database. You 'mock' the DB function to just instantly return fake data so you can test your logic.