0Pricing
Frontend Academy · Lesson

Mocking Modules and API Calls

Mock ES modules with jest.mock(), stub fetch with MSW (Mock Service Worker), and test components that depend on external data without real network calls.

Mocking Modules and API Calls is a free Frontend Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Mock?

Unit tests should be isolated. Real API calls are slow, unreliable, and costly. Mocking replaces dependencies with controlled test doubles that return predictable responses.

jest.mock() — Mock Entire Modules

jest.mock('module-path') replaces the entire module with auto-mocked versions. All exports become jest.fn() stubs. Call mockReturnValue or mockResolvedValue to set return values.

jest.mock('./api');
import { fetchUser } from './api';

(fetchUser as jest.Mock).mockResolvedValue({ id: 1, name: 'Alice' });

test('renders user name', async () => {
  render(<Profile userId="1" />);
  await screen.findByText('Alice');
  expect(fetchUser).toHaveBeenCalledWith('1');
});

jest.fn() — Manual Stubs

jest.fn() creates a mock function you can track and control. Useful for callback props and service dependencies.

const onSubmit = jest.fn();
render(<Form onSubmit={onSubmit} />);

await user.click(screen.getByRole('button', { name: /submit/i }));

expect(onSubmit).toHaveBeenCalledOnce();
expect(onSubmit).toHaveBeenCalledWith({ email: 'alice@example.com' });

beforeEach Mock Reset

Reset mocks between tests to prevent state leaking. Use jest.clearAllMocks() in beforeEach.

beforeEach(() => {
  jest.clearAllMocks(); // reset call counts and implementations
});

afterAll(() => {
  jest.restoreAllMocks(); // restore original implementations
});

MSW — Mock Service Worker

MSW intercepts real fetch/XHR calls at the network level using Service Workers (browser) or Node.js interceptors (tests). Write request handlers that return fake responses.

import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';

const server = setupServer(
  http.get('/api/users', () => {
    return HttpResponse.json([{ id: 1, name: 'Alice' }]);
  })
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

MSW per-Test Overrides

Override the default handler for a specific test scenario.

test('handles server error', async () => {
  server.use(
    http.get('/api/users', () => new HttpResponse(null, { status: 500 }))
  );

  render(<UserList />);
  await screen.findByText(/server error/i);
});

Mocking localStorage

Use jest.spyOn to mock Web Storage methods in tests that use localStorage.

beforeEach(() => {
  const store: Record<string, string> = {};
  jest.spyOn(Storage.prototype, 'getItem').mockImplementation((key) => store[key] ?? null);
  jest.spyOn(Storage.prototype, 'setItem').mockImplementation((key, val) => { store[key] = val; });
});

Mocking Timers

jest.useFakeTimers() replaces setTimeout/setInterval with Jest-controlled versions. jest.runAllTimers() fast-forwards all timers.

jest.useFakeTimers();

test('shows toast for 3 seconds', () => {
  render(<Toast message="Saved!" />);
  expect(screen.getByText('Saved!')).toBeInTheDocument();

  jest.advanceTimersByTime(3000);
  expect(screen.queryByText('Saved!')).not.toBeInTheDocument();
});

afterEach(() => jest.useRealTimers());

Module Factory Pattern

For TypeScript, mock module factories return the proper types.

jest.mock('./services/auth', () => ({
  login: jest.fn().mockResolvedValue({ token: 'test-token' }),
  logout: jest.fn()
}));

Snapshot Testing — Use Sparingly

Snapshot tests save a serialised representation of a component's output and fail if it changes. They're easy to create but can produce noisy false positives. Use only for stable, pure presentational components.

Quick Check

What is the main advantage of MSW over jest.mock('fetch') for API mocking?

Recap: Mocking

jest.mock() replaces modules. jest.fn() creates trackable stubs. Reset mocks in beforeEach. MSW intercepts HTTP at the network level — the most realistic mocking approach. Per-test server.use() overrides for error scenarios. Fake timers for time-dependent code. Prefer MSW for component integration tests.

Frequently asked questions

Is the “Mocking Modules and API Calls” lesson free?

Yes — the full text of “Mocking Modules and API Calls” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.

What will I learn in “Mocking Modules and API Calls”?

Mock ES modules with jest.mock(), stub fetch with MSW (Mock Service Worker), and test components that depend on external data without real network calls. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Frontend Academy?

No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Mocking Modules and API Calls” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Frontend Academy lesson?

Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Jest Setup and Basic Tests
  2. @testing-library/react: render userEvent
  3. @testing-library/vue: mounting components
  4. Mocking Modules and API Calls
← Back to Frontend Academy