Your checkout test calls the real payment service. Every time the test runs, the test card is charged $90, and Budi's inbox fills with "Payment received" emails. When the internet is slow, the test fails even though your code hasn't changed.
The way out is mocking: replacing the parts your code calls (such as a payment service, an email sender or a database) with stand-ins. You set the stand-in's answers, and it records how it was called. A stand-in like that is called a test double. The name comes from the stunt double in films: the person who replaces the actor in dangerous scenes, so the real actor doesn't have to jump off a building. In a test, the stunt double is the stand-in, and the real actor is the real service. The scene, which is the code you test, runs exactly as it is, but no card is charged and no email is sent.
Why you need stand-ins
processOrder below takes an order and a services object, which holds the functions pay and sendEmail:
function processOrder(order, services) {
const result = services.pay(order.total);
if (result.status === "success") {
services.sendEmail(order.email, "Payment received");
}
return result.status;
}
What we want to test is the logic: the email is only sent when the payment (pay) succeeds. If the test called the real pay and sendEmail, every run would take money, send a real email and depend on the internet. So the test passes stand-ins in services.
vi.fn(): a fake function
The test below makes two fake functions with vi.fn(), then passes both to processOrder. vi (Vitest's tools for stand-ins) is imported too:
import { describe, it, expect, vi } from "vitest";
it("sends an email when the payment succeeds", () => {
const pay = vi.fn();
pay.mockReturnValue({ status: "success" }); // we set its answer
const sendEmail = vi.fn(); // we will check how it was called
const status = processOrder({ total: 90, email: "[email protected]" }, { pay, sendEmail });
expect(status).toBe("success");
expect(pay).toHaveBeenCalledWith(90);
expect(sendEmail).toHaveBeenCalledTimes(1);
});
vi.fn()makes a fake function that does nothing (it returnsundefined), but records every call: how many times, and with which arguments. The record is inpay.mock.calls. In this test it holds[[90]]: one call, argument 90.mockReturnValue(value)makes the fake always returnvalue.mockImplementation((a, b) => a + b)gives the fake a replacement body.toHaveBeenCalled()checks that the fake was called,toHaveBeenCalledTimes(1)how many times, andtoHaveBeenCalledWith(90)with which arguments.
The opposite test, expect(sendEmail).not.toHaveBeenCalled(), checks that no email is sent when the payment fails. If processOrder sends the email anyway, that test reports:
× order.test.js > processOrder > does not send an email when the payment fails 1ms
→ expected "vi.fn()" to not be called at all, but actually been called 1 times
Behind the scenes: a home-made fake
createMock() below makes a home-made fake, like a small vi.fn():
function createMock() {
let returnValue;
function mockFn(...args) {
mockFn.callCount++; // record: called once more
mockFn.lastArgs = args; // record: the last arguments, [] when there are none
return returnValue;
}
mockFn.callCount = 0;
mockFn.lastArgs = [];
mockFn.mockReturnValue = function (val) {
returnValue = val;
};
return mockFn;
}
A function in JavaScript is also an object, so it can carry its own properties such as callCount. The code that records the calls is inside the body of mockFn, so the record updates every time mockFn is called. mockReturnValue only stores the value that body will return later. vi.fn() works the same way.
vi.spyOn: watching without replacing
A spy records the calls to a real method without replacing what it does. Below, a spy is put on math.calculate:
const math = {
calculate(a, b) {
return a + b;
},
};
const spy = vi.spyOn(math, "calculate");
const result = math.calculate(2, 3);
expect(result).toBe(5); // the real body still runs
expect(spy).toHaveBeenCalledWith(2, 3);
vi.spyOn(object, "methodName")wraps the real method: every call is recorded, and the real body still runs. So the result is 5, notundefined.- Call it through the object,
math.calculate(...), because what gets wrapped is the method on that object. - To stop the real body from running:
spy.mockImplementation(() => {}).spy.mockRestore()puts the real method back.
vi.mock: replacing a module
Below, vi.mock replaces the module (a file you import) ./utils with a stand-in:
import { formatDate } from "./utils";
vi.mock("./utils", () => ({
formatDate: vi.fn(() => "1 January 2025"),
}));
While that test file runs, every import of that module gets the fake version, including the imports inside the code you test. vi.mock is written after the import, but Vitest moves it to the very top of the file, so the fake is in place before the imports run. Use vi.mock for modules your code imports directly, not for ones passed in as a parameter, like services.
Five kinds of test double
| Kind | What it does | Example |
|---|---|---|
| Dummy | only fills a required parameter, never used | an empty object for a logger parameter nobody touches |
| Stub | gives a fixed answer | pay.mockReturnValue({ status: "success" }) |
| Spy | records calls, the real body still runs | vi.spyOn(math, "calculate") |
| Mock | replaces, then its calls are checked | expect(sendEmail).toHaveBeenCalledTimes(1) |
| Fake | a light working version | an in-memory database, an array, in place of the real database |
In Vitest, one vi.fn() can be a stub and a mock at once, like pay above. What needs no stand-in at all: a pure function (a function whose result depends only on its input) with no dependencies (other parts it calls), such as calculateTotal from the lesson The Testing Pyramid & Strategy. Just call the real one.
Clean up between tests
In Vitest 4, a fake made once at the top of the file keeps a record from every test. The second test can see calls from the first, then fail with a message like the not.toHaveBeenCalled() example above. Vitest 5 clears that record by itself before each test (the clearMocks option), but leaves every spy in place. So clean up the fakes in beforeEach and afterEach:
beforeEach(() => {
vi.clearAllMocks(); // wipe the call records of every fake
});
afterEach(() => {
vi.restoreAllMocks(); // put back the real methods that were spied on
});
⚠️ Stand-ins set up wrong
- Mocking everything. When everything is fake, you are only testing your own fakes. Fake only the parts that are slow, cost money or have side effects (they change something outside your code, such as sending an email).
- Calling through a copy. If
const calc = math.calculate;is written beforespyOn,calcstill points at the real method, socalc(2, 3)is not recorded. Callmath.calculate(2, 3). - Forgetting to clean up. Call records carry over into the next test (in Vitest 4), and spies stay installed.
- Fake-only matchers on a normal function.
expect(email.send).toHaveBeenCalled()withoutvi.fnorvi.spyOnfails with[Function send] is not a spy or a call to a spy!.
TL;DR: A test double is a stand-in for a dependency (another part your code calls) that is slow, costs money or has side effects, such as sending an email. vi.fn() makes a fake function that records its calls, mockReturnValue sets its answer, and toHaveBeenCalled, toHaveBeenCalledTimes, toHaveBeenCalledWith check its record. vi.spyOn(object, "method") records without replacing, so the real body still runs. vi.mock("./module", ...) replaces a whole module. The kinds: dummy (fills a parameter), stub (a fixed answer), spy (records without replacing), mock (its calls are checked) and fake (a light version that works). A pure function (its result depends only on its input) needs no mock. Fakes are cleaned up between tests with vi.clearAllMocks() and vi.restoreAllMocks().
⚡ vi.fn(): a fake that keeps a record
Write:
const pay = vi.fn();
pay.mockReturnValue({ status: "success" }); // we set its answer
const sendEmail = vi.fn(); // we will check how it was called
expect(pay).toHaveBeenCalledWith(90);
expect(sendEmail).toHaveBeenCalledTimes(1);
Meaning: vi.fn() makes a fake function that records every call: pay stands in for the payment service, sendEmail for the email sender. mockReturnValue sets the answer of pay. Between the two parts of this code, the test runs the checkout code, which calls both (not shown). Then toHaveBeenCalledWith checks the arguments of the call, and toHaveBeenCalledTimes the number of calls.
⚡ vi.spyOn: watching without replacing
Write:
const spy = vi.spyOn(math, "calculate");
const result = math.calculate(2, 3);
Guess first: math.calculate(a, b) returns a + b. What is in result, 5 or undefined?
It holds 5. A spy wraps the real method: the real body still runs, and the call is recorded.
Meaning: vi.spyOn(math, "calculate") puts a spy on math.calculate. Call it through the object, math.calculate(...), because what gets wrapped is the method on that object.
⚡ When you need no stand-in
Guess first: does a pure function (its result depends only on its input, and it calls no other part), such as calculateTotal, which calculates a shopping total, need a mock (a stand-in)?
No. Just call the real function.
Meaning: Fake only the parts that are slow, cost money or have side effects (they change something outside your code, such as sending an email). When everything is fake, you are only testing your own fakes.