Skip to content

Mock

In one line

A mock is a stand-in for a real dependency (like a database or API) that lets you control what it returns and verify how it was called.

In simple words

A mock is like a stunt double for a real dependency. Instead of using the real database (which is slow and might have side effects), you use a fake version that you control completely.

Mocks do two things:

  1. They replace real behavior — you can make a mock return any value you want.
  2. They record what happened — you can check how many times they were called and with what arguments.

For example, instead of calling a real API that might be slow or down, you mock it to immediately return fake data. Your test then verifies that your code handles that data correctly, without ever touching the real API.

Example

javascript
const mockFetch = jest.fn();
mockFetch.mockResolvedValue({ name: 'Alice' });

// Use the mock instead of real fetch
const result = await mockFetch();
expect(result).toEqual({ name: 'Alice' });
expect(mockFetch).toHaveBeenCalledTimes(1);

The mock replaces fetch, returns controlled data, and records that it was called once.

Common confusions

  • Confused with: Stub

    The difference: A mock verifies how it was called (expectations); a stub only provides preset return values without verification.

  • Confused with: Spy

    The difference: A spy wraps a real function and records calls while still running the original; a mock replaces the function entirely.

Related terms

Related Resources

Related Lessons

  • Mocking

    Using mocks to isolate code.

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary