React Course
React
/
Intermediate

Jest

Definition

Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It acts as the test runner, assertion library, and mocking framework all in one.

Explain Like I'm New

Jest is like the referee of a soccer game. It runs the match (test runner), blows the whistle when someone breaks the rules (assertion library), and occasionally swaps players out for practice dummies (mocking).

Real World Example

Writing `test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });` and running `npm test`. Jest finds the file, runs the code, and prints a green checkmark.

Common Use Cases

  • Unit testing JavaScript logic and utility functions
  • Mocking backend API calls so tests run without the internet
  • Snapshot testing UI components

Interactive Example

import { sum } from './math';
import axios from 'axios';

// Hoisted to the top automatically by Jest
jest.mock('axios');

describe('Math operations', () => {
  it('should add two numbers', () => {
    expect(sum(1, 2)).toBe(3);
    expect(sum(2, 2)).not.toBe(5);
  });
});

describe('API Calls', () => {
  it('should mock axios', async () => {
    // We swap out the real axios with a fake return value
    axios.get.mockResolvedValue({ data: { user: 'Alice' } });
    
    const res = await axios.get('/user');
    expect(res.data.user).toBe('Alice');
  });
});

Interview Questions

basic

  • What is the difference between Jest and React Testing Library?
  • What does `describe` and `it` mean in Jest?

intermediate

  • How do you mock an external module in Jest?
  • What is Snapshot Testing?

advanced

  • How does `jest.mock()` get hoisted to the top of the file?
  • What is the difference between `jest.fn()`, `jest.spyOn()`, and `jest.mock()`?

Flash Cards

Question

What is the difference between Jest and RTL?

Click to reveal answer
Answer

Jest is the test runner that executes the JavaScript code in Node.js and provides the `expect()` functions. React Testing Library is a set of utilities that renders the React component into a fake DOM so Jest can interact with it.

Question

What is Snapshot Testing?

Click to reveal answer
Answer

Jest takes a serialized snapshot of your rendered component and saves it to a file. On the next test run, it compares the new render to the saved file. If even a single CSS class changed, the test fails. It is useful for preventing accidental UI changes, but notorious for causing 'snapshot fatigue'.