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()`?