| | |

Vitest 09 🧪 Mock Functions — vi.fn() and Tracking Calls

⏱️ Estimated read: 9 min | |

A mock function is a function that records how it was called. It replaces a real function in a test, captures every argument and return value, and lets the test assert on the interaction rather than only on the output. Vitest’s vi.fn() creates a mock function, and the returned mock has a set of methods for configuring its behavior and inspecting its calls. The mock is the tool for testing the boundary between the unit and its dependencies—a callback, an API client, a database method—without invoking the real dependency.

This chapter covers the vi.fn() API, the call-tracking methods that record the arguments and the return value, and the configuration methods that set the mock’s behavior. The sections that follow walk through the mock function, the call inspection, and the matchers that assert on a mock’s interactions.

Key point: vi.fn() creates a mock function that records every call; .mock.calls and the toHaveBeenCalledWith matchers assert on the arguments, .mockReturnValue and .mockResolvedValue set the behavior, and vi.restoreAllMocks() or restoreMocks: true resets the mock between tests.


a. Creating a mock function and setting its behavior

vi.fn() returns a mock function. Without a configuration, it returns undefined when called. The mockImplementation method sets the function body, mockReturnValue sets a constant return, and mockResolvedValue sets a resolved Promise for an async mock.

import { vi, expect, test } from "vitest";

// A mock that returns undefined
const noop = vi.fn();

// A mock with an implementation
const add = vi.fn((a: number, b: number) => a + b);

// A mock that returns a constant
const getConfig = vi.fn().mockReturnValue({ debug: true });

// A mock that resolves a Promise
const fetchUser = vi.fn().mockResolvedValue({ id: "1", name: "Ana" });

// A mock that rejects
const fail = vi.fn().mockRejectedValue(new Error("nope"));

// Chained: one return per call, last value repeats
const sequence = vi.fn()
  .mockReturnValueOnce("first")
  .mockReturnValueOnce("second")
  .mockReturnValue("rest");

The mockImplementation form is for a mock that needs logic; the mockReturnValue form is for a constant; the mockResolvedValue form is for an async function that always succeeds. The Once variants set the return for a single call and fall through to the next configuration, which is how a mock produces a different result on the first and second calls.

The mock can also be created with the implementation in the call: vi.fn((a, b) => a + b). The two forms are equivalent, and the choice is style.


b. Inspecting the calls

The mock records every call in .mock.calls, every return value in .mock.results, and the this context in .mock.contexts. The properties are arrays, and each index corresponds to the call order.

const log = vi.fn();

log("hello");
log("world", 42);

// Calls: [["hello"], ["world", 42]]
expect(log.mock.calls).toEqual([["hello"], ["world", 42]]);

// First call's first argument
expect(log.mock.calls[0][0]).toBe("hello");

// Number of calls
expect(log).toHaveBeenCalledTimes(2);

// Called with specific arguments (any call)
expect(log).toHaveBeenCalledWith("hello");
expect(log).toHaveBeenCalledWith("world", 42);

// Last call
expect(log).toHaveBeenLastCalledWith("world", 42);

// Nth call
expect(log).toHaveBeenNthCalledWith(1, "hello");

The toHaveBeenCalledWith matcher checks whether any call matched the arguments; toHaveBeenLastCalledWith checks the last call; toHaveBeenNthCalledWith checks a specific position. The toHaveBeenCalledTimes(n) matcher checks the count. The toHaveBeenCalled() matcher is the shorthand for “at least one call”.

The .mock.results array records the return value of each call, with a type of "return" or "throw" and the value. It is the way to assert on what the mock returned, rather than on what it was called with.

const fn = vi.fn().mockReturnValue(42);
fn();

expect(fn.mock.results[0]).toEqual({ type: "return", value: 42 });

c. Clearing, resetting, and restoring

The mock accumulates state across tests unless it is reset. The three reset methods have different scopes: mockClear() clears the call history but keeps the implementation; mockReset() clears the history and the implementation; mockRestore() restores the original function if the mock was created with vi.spyOn().

const fn = vi.fn().mockReturnValue(42);

fn();
fn.mockClear();   // history cleared, still returns 42
fn.mockReset();   // history and implementation cleared, returns undefined

The vi.clearAllMocks(), vi.resetAllMocks(), and vi.restoreAllMocks() functions apply the same operations to every mock in the test file. The config options clearMocks, resetMocks, and restoreMocks run the corresponding function before each test automatically.

// vitest.config.ts
export default defineConfig({
  test: {
    clearMocks: true,   // vi.clearAllMocks() before each test
    restoreMocks: true, // vi.restoreAllMocks() before each test
  },
});

The distinction that matters is clearMocks versus resetMocks. clearMocks keeps the implementation, so a mock that returns 42 still returns 42 in the next test. resetMocks removes the implementation, so the mock returns undefined until it is configured again. A test that relies on a mock’s return value but forgets to configure it in every test will fail with resetMocks: true and pass with clearMocks: true.

The vi.spyOn() method creates a mock that wraps an existing method on an object. The spy calls the original by default and records the call. mockRestore() removes the spy and restores the original method, which is why restoreMocks: true is the correct setting for a suite that uses spies.

const obj = { greet: (name: string) => `Hello, ${name}` };
const spy = vi.spyOn(obj, "greet");

obj.greet("Ana");
expect(spy).toHaveBeenCalledWith("Ana");
spy.mockRestore(); // restores the original greet

Complete Example Session

// ============================================
// PART 1: THE MODULE UNDER TEST
// ============================================
// src/user-service.ts
export async function createUser(
  api: { post: (path: string, body: unknown) => Promise<unknown> },
  data: { name: string }
) {
  return api.post("/users", data);
}

// ============================================
// PART 2: THE MOCK
// ============================================
import { vi, describe, it, expect } from "vitest";
import { createUser } from "./user-service";

describe("createUser", () => {
  it("calls the API with the user data", async () => {
    const api = {
      post: vi.fn().mockResolvedValue({ id: "1", name: "Ana" }),
    };

    const result = await createUser(api, { name: "Ana" });

    expect(api.post).toHaveBeenCalledTimes(1);
    expect(api.post).toHaveBeenCalledWith("/users", { name: "Ana" });
    expect(result).toEqual({ id: "1", name: "Ana" });
  });
});

// ============================================
// PART 3: SEQUENCE OF RETURNS
// ============================================
describe("sequence", () => {
  it("returns different values per call", () => {
    const fn = vi.fn()
      .mockReturnValueOnce("first")
      .mockReturnValueOnce("second");

    expect(fn()).toBe("first");
    expect(fn()).toBe("second");
    expect(fn()).toBeUndefined();
  });
});

// ============================================
// PART 4: THE RESET
// ============================================
describe("reset", () => {
  it("clears the call history", () => {
    const fn = vi.fn();
    fn("a");
    fn.mockClear();
    expect(fn).not.toHaveBeenCalled();
  });
});

The parts covered the module, the mock with a resolved value, the sequence of returns, and the reset.


Quick Reference

Mock Creation

CallBehavior
vi.fn()Returns undefined
vi.fn((a) => a * 2)With implementation
.mockReturnValue(v)Constant return
.mockResolvedValue(v)Resolved Promise
.mockRejectedValue(e)Rejected Promise
.mockReturnValueOnce(v)One call only

Call Inspection

Property/MatcherAsserts
mock.callsArray of argument arrays
mock.resultsArray of return/throw records
toHaveBeenCalled()At least one call
toHaveBeenCalledTimes(n)Exact count
toHaveBeenCalledWith(...)Any call matches
toHaveBeenLastCalledWith(...)Last call matches
toHaveBeenNthCalledWith(n, ...)Nth call matches

Reset Methods

MethodClears HistoryClears Implementation
mockClear()YesNo
mockReset()YesYes
mockRestore()YesRestores original (spy)

Best Practices

✅ Do This:

// Configure the mock's behavior per test
const api = { post: vi.fn().mockResolvedValue(data) };         // ✅

// Assert on the arguments
expect(api.post).toHaveBeenCalledWith("/users", { name: "Ana" }); // ✅

// Restore spies
test: { restoreMocks: true }                                   // ✅

❌ Don’t Do This:

// Share a configured mock across tests without reset
const mock = vi.fn().mockReturnValue(42); // module-level       // ❌

// Use resetMocks when the mock needs its implementation
test: { resetMocks: true } // every test reconfigures           // ❌

// Assert on the mock without configuring it
expect(mock()).toBe(42); // undefined unless configured         // ❌

Common Pitfalls

PitfallWhy It HappensFix
Mock returns undefinedresetMocks: true cleared the implementationConfigure per test or use clearMocks
Call history leaksNo reset between testsclearMocks: true
Spy stays after testNo restorerestoreMocks: true
toHaveBeenCalledWith passes on the wrong callMatches any callUse toHaveBeenLastCalledWith

Real-World Examples

1. Basic mock

const fn = vi.fn();

2. Mock with implementation

const add = vi.fn((a, b) => a + b);

3. Resolved value

const fetchUser = vi.fn().mockResolvedValue({ id: "1" });

4. Sequence

vi.fn().mockReturnValueOnce(1).mockReturnValue(2);

5. Call count

expect(fn).toHaveBeenCalledTimes(2);

6. Called with

expect(fn).toHaveBeenCalledWith("a", 1);

7. Last call

expect(fn).toHaveBeenLastCalledWith("b");

8. Spy

const spy = vi.spyOn(obj, "method");

9. Restore

spy.mockRestore();

10. Config reset

test: { clearMocks: true, restoreMocks: true }

Visual

The Mock’s Lifecycle

┌─────────────────────────────────────────────────────────┐
│  vi.fn()                                                │
│         │                                               │
│         ▼                                               │
│  Configure: mockReturnValue / mockResolvedValue         │
│         │                                               │
│         ▼                                               │
│  Call: records args in mock.calls                       │
│         │                                               │
│         ▼                                               │
│  Assert: toHaveBeenCalledWith / toHaveBeenCalledTimes   │
│         │                                               │
│         ▼                                               │
│  Reset: mockClear / mockReset / restoreMocks            │
└─────────────────────────────────────────────────────────┘

Clear vs Reset

┌─────────────────────────────────────────────────────────┐
│  const fn = vi.fn().mockReturnValue(42);                │
│  fn();                                                  │
│                                                         │
│  mockClear()                                            │
│    calls: []        return: 42                          │
│                                                         │
│  mockReset()                                            │
│    calls: []        return: undefined                   │
└─────────────────────────────────────────────────────────┘

Spy Flow

┌─────────────────────────────────────────────────────────┐
│  vi.spyOn(obj, "method")                                │
│         │                                               │
│         ▼                                               │
│  Calls the original method by default                   │
│         │                                               │
│         ▼                                               │
│  Records the call                                       │
│         │                                               │
│         ▼                                               │
│  mockRestore() → original method restored               │
└─────────────────────────────────────────────────────────┘

Config Interaction

┌─────────────────────────────────────────────────────────┐
│  clearMocks: true                                       │
│    history cleared, implementation kept                 │
│                                                         │
│  resetMocks: true                                       │
│    history and implementation cleared                   │
│    → every test must reconfigure its mocks              │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Createvi.fn()
Implementationvi.fn((a) => a * 2)
Constant return.mockReturnValue(v)
Async return.mockResolvedValue(v)
Call historymock.calls
Call matcherstoHaveBeenCalledWith, toHaveBeenCalledTimes
ClearmockClear()
ResetmockReset()
Spyvi.spyOn(obj, "method")

Key takeaways:

  • A mock function records every call. vi.fn() returns a function that tracks its arguments in mock.calls and its returns in mock.results, and the toHaveBeenCalledWith matchers assert on those records.
  • The behavior is configured per test. mockReturnValue, mockResolvedValue, and the Once variants set what the mock returns. A mock that is not configured returns undefined.
  • clearMocks keeps the implementation; resetMocks removes it. A suite that configures its mocks in beforeEach can use resetMocks; a suite that configures them at module level needs clearMocks.
  • vi.spyOn() wraps an existing method. The spy calls the original by default and records the call; mockRestore() removes the spy and restores the original.
  • The toHaveBeenCalledWith matcher passes if any call matches. Use toHaveBeenLastCalledWith or toHaveBeenNthCalledWith when the specific call matters.

Remember: A mock is a function that remembers. It replaces the dependency, records the interaction, and lets the test assert on the boundary rather than the implementation. Configure the return, assert on the calls, and reset between tests. The three reset methods differ in what they clear, and the config option determines which one runs automatically. A mock that leaks its call history or its implementation produces a test that passes for the wrong reason.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!