JavaScript › Debugging, Testing & Tooling

How does Jest's mocking help isolate the code under test?

Intermediate

Answer

jest.fn() and jest.mock() replace real dependencies (API calls, modules, timers) with controllable fake implementations, so tests can verify how your code calls those dependencies without triggering real network requests or side effects.
const fetchUser = jest.fn().mockResolvedValue({ name: 'Sam' });
await fetchUser();
expect(fetchUser).toHaveBeenCalledTimes(1);
Real-world example Testing a component that fetches user data without hitting a real API in CI.

Common follow-ups: What's the difference between a mock, a stub, and a spy?