Skip to content

Mocks

Create and verify mocks to replace dependencies and assert interactions in your tests.

What you'll learn

  • How to create a mock function with vi.fn and jest.fn
  • Setting return values and resolved promises on mocks
  • Asserting call count, arguments, and call order
  • Mocking entire modules with vi.mock and jest.mock

Concept

Creating a Mock Function

A mock function is a callable that records every call made to it — its arguments, return value, and the order relative to other mocks. In Vitest use vi.fn(), in Jest jest.fn(). By default it returns undefined; you configure it with mockReturnValue, mockResolvedValue (for promises), or mockImplementation for custom logic.

Asserting Interactions

Once the code under test has run, you assert on the mock's recorded calls: toHaveBeenCalledTimes(1), toHaveBeenCalledWith(arg1, arg2), toHaveBeenLastCalledWith(...), or toHaveBeenNthCalledWith(2, ...). These assertions verify that your code interacted with its dependency correctly — the contract — without depending on the dependency's real behavior.

Mocking Modules

Sometimes you need to replace an entire imported module, like fs or an API client. vi.mock("modulePath", factory) (and jest.mock) replaces the module with your factory before any test imports it. This is powerful but hoisted — the factory runs before imports, so you cannot reference local variables in it directly. Use vi.hoisted or define the factory inline to avoid reference errors.

When to Mock

Mock at the seams where your code talks to the outside world: the filesystem, network, database, clock, or random source. Mocking your own pure functions is usually a smell — it couples the test to call sites rather than behavior. Prefer to mock the thin adapter layer and let your domain logic run for real beneath it.

In Practice

When mocking modules, remember that vi.mock is hoisted above imports — the factory runs before any import statement, so you cannot reference variables declared with const at module top level inside it. Use vi.hoisted to declare shared values that the factory can safely access. After each test, clear mock state with vi.clearAllMocks() (resets call records) or vi.resetAllMocks() (also removes implementations) so call counts and arguments never leak between tests. For partial mocks, use vi.mock with vi.importActual to keep most of a module real while replacing only the function you need. Read the failure messages carefully: a mock that was never called tells you the code took a different path than you expected, which is often the real bug rather than a test problem.

Example

              import { describe, it, expect, vi } from "vitest";

// Mock a module before imports are evaluated
vi.mock("./api", () => ({
  fetchUser: vi.fn().mockResolvedValue({ id: 7, name: "Bo" }),
}));

import { fetchUser } from "./api";
import { getDisplayName } from "./profile";

describe("getDisplayName", () => {
  it("returns the user's name from the API", async () => {
    const name = await getDisplayName(7);
    expect(name).toBe("Bo");
    expect(fetchUser).toHaveBeenCalledWith(7);
  });
});
            

vi.mock replaces the real api module with a fake whose fetchUser resolves immediately. The test verifies both the result and that the API was called with the right id.

Try it

Common mistakes

The mistake

Referencing outer variables inside vi.mock factory

The fix

vi.mock is hoisted above imports, so outer consts are not yet defined. Use vi.hoisted(() => ...) to share values safely.

The mistake

Forgetting to reset mocks between tests

The fix

Add beforeEach(() => vi.clearAllMocks()) so call counts and arguments from one test do not leak into the next.

Practice Mocks

13 exercises

Practice Mocks

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

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

View errors