Vitest 10 🧪 Spying on Methods — vi.spyOn() and restoring originals
vi.spyOn(object, "method") creates a mock that wraps an existing method on an object. It records every call, and it calls the original method by default. The difference from vi.fn() is that the spy is attached to a real object and preserves the original behavior unless the test replaces it. The difference from vi.mock() is that the spy operates on a single method, not a whole module, and it can be restored with mockRestore().
This chapter covers the vi.spyOn() API, the default call-through behavior, the replacement and restore lifecycle, and the cases where a spy is the wrong tool. The sections that follow walk through the spy’s creation, the mockImplementation replacement, and the restoreAllMocks configuration that prevents the spy from leaking into the next test.
Key point: vi.spyOn(obj, "method") wraps the method, records calls, and calls the original by default; mockImplementation replaces the original, and mockRestore() (or restoreMocks: true) removes the spy and restores the original method.
a. Creating a spy and the call-through default
vi.spyOn(object, "method") returns a spy that is installed on the object. The spy records the call and, by default, invokes the original method with the same arguments and returns its result. This is the difference from vi.fn(), which has no original to call.
import { vi, expect, test } from "vitest";
const calculator = {
add(a: number, b: number) {
return a + b;
},
};
test("spies on add without changing it", () => {
const spy = vi.spyOn(calculator, "add");
const result = calculator.add(2, 3);
expect(result).toBe(5); // original still runs
expect(spy).toHaveBeenCalledWith(2, 3); // call recorded
});
The spy is installed on the object, not on a copy. A call to calculator.add() after vi.spyOn goes through the spy, and the spy’s call history records it. The original method is still callable, which is why the result is 5.
The spy works on any object with a method: a class instance, a module’s exported object, console, window, document. The vi.spyOn(console, "log") spy is the standard way to assert that code logged a message without polluting the test output.
const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
// code that calls console.log
expect(logSpy).toHaveBeenCalledWith("expected message");
The mockImplementation(() => {}) is what silences the log while still recording the call. Without it, the spy calls the original console.log and the message appears in the test output.
b. Replacing the implementation and restoring
mockImplementation replaces the original method body. mockReturnValue replaces the return without changing the arguments. mockResolvedValue does the same for an async method.
const api = {
async fetchUser(id: string) {
return { id, name: "Real" };
},
};
test("replaces the API call", async () => {
const spy = vi.spyOn(api, "fetchUser").mockResolvedValue({
id: "1",
name: "Mocked",
});
const user = await api.fetchUser("1");
expect(user.name).toBe("Mocked"); // original not called
expect(spy).toHaveBeenCalledWith("1");
});
The replacement is in place until mockRestore() is called. A spy that is not restored stays installed on the object for the rest of the test file, and the next test that calls the method gets the mocked behavior. This is the leak that restoreMocks: true prevents.
test("restores the original", () => {
const spy = vi.spyOn(calculator, "add").mockReturnValue(99);
expect(calculator.add(1, 1)).toBe(99);
spy.mockRestore();
expect(calculator.add(1, 1)).toBe(2); // original restored
});
The mockRestore() method does two things: it clears the call history and it restores the original method. The mockReset() method clears the history and removes the implementation, but it does not restore the original—the spy remains installed and returns undefined. The distinction matters when the spy is on an object that other tests depend on.
c. The restore lifecycle and the configuration
The restoreMocks: true configuration option runs vi.restoreAllMocks() before each test. It restores every spy created with vi.spyOn() and resets every mock created with vi.fn() to its original state. The option is the recommended setting for a suite that uses spies, because it removes the need to call mockRestore() at the end of every test.
// vitest.config.ts
export default defineConfig({
test: {
restoreMocks: true,
},
});
The vi.restoreAllMocks() function can also be called explicitly in an afterEach hook. The configuration option is the same operation, applied automatically, and it is the pattern that keeps a spy from leaking into the next test.
The spy is the wrong tool when the entire module needs to be replaced. vi.mock("./module") replaces the module’s exports for the whole test file, which is the correct pattern for a dependency that every test in the file needs to control. A spy is for a single method on an object that the test can access directly, and it is the lighter-weight option because it does not require the module mock’s hoisting or the __mocks__ directory.
The spy is also the wrong tool when the method is a getter or a property that is not a function. vi.spyOn(obj, "prop", "get") can spy on a getter, and the third argument is the access type, but a plain property cannot be spied on without the access type. The vi.spyOn documentation covers the access type argument for getters and setters.
Complete Example Session
// ============================================
// PART 1: THE OBJECT UNDER TEST
// ============================================
// src/notifier.ts
export const notifier = {
send(email: string, message: string) {
console.log(`Sending to ${email}: ${message}`);
},
};
export function notifyUser(email: string) {
notifier.send(email, "Welcome!");
}
// ============================================
// PART 2: THE SPY (CALL-THROUGH)
// ============================================
import { vi, describe, it, expect } from "vitest";
import { notifier, notifyUser } from "./notifier";
describe("notifyUser", () => {
it("calls notifier.send with the email", () => {
const spy = vi.spyOn(notifier, "send").mockImplementation(() => {});
notifyUser("a@b.com");
expect(spy).toHaveBeenCalledWith("a@b.com", "Welcome!");
spy.mockRestore();
});
});
// ============================================
// PART 3: THE REPLACEMENT
// ============================================
describe("replacement", () => {
it("replaces the send implementation", () => {
const spy = vi.spyOn(notifier, "send").mockImplementation(() => {
throw new Error("network down");
});
expect(() => notifyUser("a@b.com")).toThrow("network down");
spy.mockRestore();
});
});
// ============================================
// PART 4: THE CONFIG-BASED RESTORE
// ============================================
// vitest.config.ts
// test: { restoreMocks: true }
//
// Every spy is restored before the next test.
The parts covered the call-through spy, the replacement, and the config-based restore.
Quick Reference
Spy API
| Call | Effect |
|---|---|
vi.spyOn(obj, "method") | Wraps, records, calls original |
.mockImplementation(fn) | Replaces the body |
.mockReturnValue(v) | Replaces the return |
.mockResolvedValue(v) | Replaces the return with a resolved Promise |
.mockRestore() | Removes the spy, restores original |
.mockReset() | Clears history and implementation |
Access Types
| Third Argument | Spies On |
|---|---|
| (none) | Method |
"get" | Getter |
"set" | Setter |
Restore Options
| Option | Effect |
|---|---|
restoreMocks: true | vi.restoreAllMocks() before each test |
mockRestore() | Restores one spy |
vi.restoreAllMocks() | Restores all spies |
Best Practices
✅ Do This:
// Spy and silence the output
const spy = vi.spyOn(console, "log").mockImplementation(() => {}); // ✅
// Restore after the test
spy.mockRestore(); // ✅
// Or configure the global restore
test: { restoreMocks: true } // ✅
❌ Don’t Do This:
// Spy without restoring
vi.spyOn(obj, "method"); // leaks into the next test // ❌
// Use mockReset expecting the original restored
spy.mockReset(); // spy still installed, returns undefined // ❌
// Spy on a whole module
vi.spyOn(module, "export"); // use vi.mock instead // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Next test gets mocked behavior | Spy not restored | restoreMocks: true |
mockReset does not restore | Clears implementation, not the spy | Use mockRestore() |
| Original still logs | No mockImplementation | Silence the original |
| Getter not spied | Missing access type | vi.spyOn(obj, "prop", "get") |
Real-World Examples
1. Call-through spy
const spy = vi.spyOn(calculator, "add");
calculator.add(1, 2);
expect(spy).toHaveBeenCalledWith(1, 2);
2. Replace return
vi.spyOn(api, "fetchUser").mockResolvedValue({ id: "1" });
3. Silence console
vi.spyOn(console, "log").mockImplementation(() => {});
4. Restore
spy.mockRestore();
5. Global restore
test: { restoreMocks: true }
6. Getter spy
vi.spyOn(obj, "prop", "get").mockReturnValue(42);
7. Throw
vi.spyOn(api, "post").mockRejectedValue(new Error("fail"));
8. Once
vi.spyOn(api, "get").mockReturnValueOnce(1).mockReturnValue(2);
9. Assert call
expect(spy).toHaveBeenCalledWith("a@b.com", "Welcome!");
10. Explicit restore in afterEach
afterEach(() => { vi.restoreAllMocks(); });
Visual
Spy Lifecycle
┌─────────────────────────────────────────────────────────┐
│ vi.spyOn(obj, "method") │
│ │ │
│ ▼ │
│ Spy installed, calls original by default │
│ │ │
│ ├──► mockImplementation → original replaced │
│ │ │
│ ▼ │
│ Call recorded in mock.calls │
│ │ │
│ ▼ │
│ mockRestore() → original method restored │
└─────────────────────────────────────────────────────────┘
Spy vs Mock vs Module Mock
┌─────────────────────────────────────────────────────────┐
│ vi.fn() Standalone mock, no original │
│ vi.spyOn() Wraps an object method │
│ vi.mock() Replaces a whole module │
│ │
│ Spy: single method, original callable, restorable │
│ Module: whole file, hoisted, __mocks__ or factory │
└─────────────────────────────────────────────────────────┘
Restore vs Reset
┌─────────────────────────────────────────────────────────┐
│ mockRestore() │
│ history cleared │
│ implementation: original │
│ spy removed │
│ │
│ mockReset() │
│ history cleared │
│ implementation: undefined │
│ spy still installed │
└─────────────────────────────────────────────────────────┘
The Leak
┌─────────────────────────────────────────────────────────┐
│ Test 1: vi.spyOn(api, "get").mockReturnValue("mocked") │
│ → api.get() returns "mocked" │
│ │
│ Test 2: api.get() │
│ → still returns "mocked" (leaked) │
│ │
│ Fix: restoreMocks: true, or mockRestore() in test 1 │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Create | vi.spyOn(obj, "method") |
| Default behavior | Calls the original |
| Replace | .mockImplementation(fn) |
| Restore | .mockRestore() |
| Reset | .mockReset() (spy remains) |
| Global restore | restoreMocks: true |
| Getter spy | vi.spyOn(obj, "prop", "get") |
Key takeaways:
- A spy wraps an object’s method and calls the original by default. The difference from
vi.fn()is that the spy is attached to a real object, and the original behavior is preserved unless the test replaces it. mockImplementationreplaces the original;mockRestoreremoves the spy. The restore is what prevents the mocked behavior from leaking into the next test.mockResetis notmockRestore. Reset clears the history and the implementation but leaves the spy installed, so the method returnsundefined. Restore removes the spy and returns the original.restoreMocks: trueis the safe default for a suite that uses spies. It runsvi.restoreAllMocks()before each test, so no spy survives into the next test.- Use
vi.mock()for whole modules andvi.spyOn()for single methods. The spy is the lighter-weight option when the test can access the object directly; the module mock is for a dependency that every test in the file needs to control.
Remember: A spy is a wrapper, not a replacement. It records the call and calls the original until the test says otherwise. The restore is the part that keeps the wrapper from becoming permanent. Call mockRestore(), or set restoreMocks: true, and remember that mockReset leaves the spy in place. The leak is silent: the next test passes or fails against a method that is not the real one.
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!