Don't let test doubles lie for you: mock strategy for AI-generated code
AI will happily mock everything, including your own code. This guide follows the Vitest and Jest official docs through test doubles: stubs, mocks, fakes and spies, function and module doubles, time and globals, three ways doubles lie, and five anti-patterns, with a pre-handover checklist.

First, the boundaries. This site already has several guides about testing, but none of them is about test doubles. The AI testing strategy guide covers "what to test, and how far" — the strategy layer. The end-to-end testing guide covers "walk the main flow from start to finish" — the whole chain. The contract testing guide covers "don't let an agreed interface quietly change" — the interface layer. This guide is about one concrete action in unit testing: the code under test depends on something — a network request, a database, the clock, a third-party API — that is unavailable, too slow, or unstable, so you put a temporary stand-in in its place. That stand-in is called a test double. Pick the wrong double and the greenest test suite is self-deception; pick the right one and the pile of AI-generated test code actually means something.
The "Ledger" app used below is a fictional practice project: a small bookkeeping app that records expenses, totals them by category, and reminds the user to reconcile before a deadline. Every action, code snippet, and number built around it in this article was invented to explain the method. It is not a real record. All interface names, behaviors, and cautions for Vitest and Jest come from the two projects' official documentation; the sources are in each article's meta information and evidence record. Other test frameworks have their own mocking syntax. The thinking is the same, but the interface names differ, so check that framework's own documentation before copying anything over.
Doubles are not one thing: four roles to tell apart first
Many people call every double a "mock," and that is where the confusion starts. There are four kinds of test doubles, each doing a different job. Get the names wrong and the choice will be wrong too. Learn the four roles first.
The first is the stub. It only answers with a fixed reply. The code under test asks it "what day is it today," and it always answers "1 January 2026"; ask it "what is the user's name," and it always answers "A-Tang." It keeps no books, does not care how many times you asked, or in what order. When you use one, the only thing you care about is "given this answer, does the code under test compute the right thing?" Vitest's vi.fn().mockReturnValue() and Jest's jest.fn().mockReturnValue() are both stubs: pin the return value first, then watch how the code under test handles it.
The second is the mock. It does everything a stub does, plus one more thing: it keeps books. It not only answers, it writes down "how you asked me" — how many times it was called, what arguments each call carried, what it returned. After the test you can check those books: "when saving a ledger entry, how many times was the save API actually called? Was the amount right each time?" The Jest documentation says this plainly in its opening: the value of a mock function is in "testing the links between code" — it erases the real implementation, captures the calls, captures the parameters, captures constructor instances, and lets you configure return values at test time. Vitest's vi.fn() works the same way: mock.calls holds every call.
The third is the fake. It is a simplified version that really runs. A real database is too heavy, so you write a fake one that lives in memory: it can store, fetch, and query by condition — losing its data does not matter, because it disappears when the test ends. A fake differs from a stub in that a stub only recites answers, while a fake really has logic; it differs from a mock in that you normally do not check its call books — you check "is the state right after it ran?"
The fourth is the spy. It changes nothing and only watches. The code under test still calls the real function, with the spy standing beside it noting "called how many times, with what." Vitest's vi.spyOn() and Jest's jest.spyOn() are exactly this: the real logic runs as usual, only with an extra pair of eyes. A spy fits best where "the implementation itself is fine, I only want to confirm it was called" — for example, confirming that "after the user hits save, the sync API really was called once," rather than "how the sync API works inside."
How do you remember the four? One sentence: if you only care about the answer, use a stub; if you also need to check the call books, use a mock; if you need a runnable simplified version, use a fake; if the implementation is fine and you only want to confirm it was called, use a spy. Before choosing, ask yourself "what exactly do I want to check?" — a different answer means a different double.

Three questions before you start: replace or not, at which layer, how real
The easiest mistake AI makes when writing tests is to mock every dependency on sight. Left to itself, it will replace the database, the network, the clock, the random numbers, and even your own utility functions, until the only thing left being tested is an empty sentence: "the code called a fake it wrote itself, and the fake returned an answer it wrote itself." Before you start, ask three questions.
Question one: should this dependency be replaced at all? The test is "is it stable, fast, and yours?" Stable, fast, and yours — don't replace it: pure functions, your own utility functions, in-memory data structures, use the real thing. Slow, unstable, or not yours — worth replacing: network requests, a real database, a third-party payment API, the system clock, random numbers. If you cannot draw this line, tests get faker the more you write. AI-generated tests need this check most: the model cannot tell "your code" from "someone else's service," so you have to draw the line for it.
Question two: at which layer do you replace it? The same dependency can be replaced at different layers. The Ledger app calls an exchange-rate API, and you can intervene at three layers: at the outermost layer, replace the whole HTTP client so it returns a hard-coded rate; at the middle layer, replace the exchange-rate service module, leaving one function that returns a fixed value; at the innermost layer, replace only the random-number generator and let the rate calculation run for real. The further out the layer, the further the test sits from reality; the further in, the more brittle the test and the bigger the change. The rule of thumb: replace the outermost layer first — network, disk, clock, the boundaries — and let the logic inside run as real as possible. Once the boundary is replaced and the logic stays real, the test is worth something.
Question three: how real should the double be? A double is not better for being more realistic. The simpler a stub's answer, the easier the test is to read and the harder it is to break. Stubbing an exchange-rate API, one fixed value — "7.2" — is enough; there is no need to copy the whole real rate table into the test. The same goes for fakes: an in-memory fake database only needs to store and fetch; do not re-implement the real database's indexes, transactions, and locks. You are building scaffolding for a test, not rewriting a database. The more realistic the double, the higher the maintenance cost: the day the real API changes, your double has to change with it, and if you miss one, the test starts lying.
Two approaches: function doubles and module doubles
The Vitest and Jest documentation split double-writing into two broad kinds: function level and module level. Function level is when you already have a function and want to swap it temporarily inside a test; module level is when a whole module — say, a file dedicated to calling an API — is swapped as a block. The commands differ; do not mix them up.
At function level, the workhorse is vi.fn() in Vitest and jest.fn() in Jest. It creates an empty function, and you pin its return value with mockReturnValue, or use mockReturnValueOnce so it answers "this the first time, that the second time, and the default after that." The Jest documentation's example is easy to follow: myMock.mockReturnValueOnce(10).mockReturnValueOnce('x').mockReturnValue(true) — call it four times in a row and you get 10, 'x', true, true. Having consecutive calls return different values fits retry logic best: make the first call fail and the second succeed, and see whether the code under test really retries once, instead of giving up after a single attempt.
Function level also has mockImplementation: it replaces not just the return value but the whole implementation. The Jest documentation adds a very practical warning: try not to put logic inside a mock function. The more logic a mock holds, the more you are testing the mock itself rather than the code under test. When you need "this the first time, that the second time," queue it with mockImplementationOnce; once the queue runs out, it falls back to the default implementation set in jest.fn(). Remember the queue rule: first in, first out, and gone once used.
At module level, the tools are vi.mock() and jest.mock(). The Jest documentation's classic example tests a class that fetches a user list with axios: write jest.mock('axios') in the test, and the whole axios module is swapped for a mock; then axios.get.mockResolvedValue({data: users}) makes it return the fake data you prepared. The code under test does not change by a line, and not one real network request goes out. Vitest's vi.mock() works the same way, but it has one iron rule to remember: a vi.mock call is hoisted to the top of the file and always runs before all imports. So the mock factory cannot reference variables defined at the top of the file — they do not exist yet when the factory runs. AI-generated tests trip over this constantly: the factory references fake data defined outside, and the run fails with "variable not initialized." If the factory needs data, either write the data inside the factory, or lift the variable with vi.hoisted().
Module doubles also have a finer variant: replace only part of a module. The Vitest documentation gives the standard pattern: the factory function of vi.mock receives an importOriginal argument; first await importOriginal() to get the real module, then spread it and swap only the one export you want to replace with vi.fn(), keeping the rest as they are. The Jest equivalent is jest.requireActual(). This is the right move for "a module with ten functions, and I only want to replace one": replace all of them and you are no longer testing your code; replace one and the other nine stay real. The official documentation also warns about a trap that is easy to step into: this "partial mock" only affects calls coming in from outside the module. If the module calls the replaced function internally, it calls the original implementation, not your mock. To replace an internal call, split that function out, or use a different replacement.
// Replace only fetchRate in the rates module; keep the other exports real
vi.mock('./rates.js', async (importOriginal) => {
const mod = await importOriginal();
return { ...mod, fetchRate: vi.fn(() => Promise.resolve(7.2)) };
});
Time, random numbers, and globals: the three doubles most often missed
Three kinds of dependency are missed most often, because they hide inside the code and are less visible than a network request: time, random numbers, and global variables. AI-generated tests love to miss all three — the model sees new Date() and finds nothing wrong with it, but whether the test passes on the second day is pure luck.
Pin time down with vi.setSystemTime(). The Vitest documentation's pattern is: build a new Date(2022, 0, 1), call vi.setSystemTime(mockDate), and from then on every new Date() in the code returns that fixed time. "Month-end summary" logic in the Ledger app can only be tested reliably this way: without pinning the clock, a test run at month-end and one at month-start give different results. But the documentation also warns that pinned time does not reset itself between tests — put it back with vi.useRealTimers() when you are done, or the next test will still read the time you pinned. And one more thing: vi.useFakeTimers() changes the Date time too, so do not mix the two approaches; pick one.
Random numbers and globals follow the same idea: do not let a test result depend on "whatever was rolled this time." Vitest offers vi.stubGlobal() to temporarily change a global variable, and you must put it back with vi.unstubAllGlobals() — or turn on the unstubGlobals config option so it resets automatically. Environment variables use vi.stubEnv(), with unstubEnvs for automatic reset. The rule is one sentence: whatever you temporarily change, the test must give it back when it ends. The Vitest documentation puts a warning at the very top of its mocking guide: always clear or restore mocks before or after each test run, to undo mock state changes between runs. The plain meaning: double state leaks between tests.
Network requests deserve a note of their own. The cheapest approach is to replace the HTTP client module (the axios example in the previous section) so it returns hard-coded fake data; to test more realistically, you can use a request-interception tool that works at the layer where "the request really goes out, but is caught locally." Either way, the test is the same: no real network request should happen inside a test. A test that waits three seconds per run, or turns red entirely when the network drops, is a test nobody wants to run — and in the end someone will delete it.
Three ways doubles lie: all green in tests, all red in production
The greatest danger of a double is not that it is "done badly" but that it is "done too well" — the tests are all green, you believe the code is fine, and only in production do you learn the double has been lying for the real code all along. Three lies show up most often, and they appear in almost every round of AI-generated tests.
Lie one: the double has drifted from reality. The real API changed long ago, but the double still returns data the old way. The Ledger app's exchange-rate API used to return {rate: 7.2} and later changed to {rate: 7.2, updatedAt: '...'}; the code under test was updated to read the new field, but the mock still returns the old shape and the tests stay green — because the code under test reads the old data the mock hands it. In production, the real API returns the new shape, the code reads a different field, and it errors out. The cure: the shape of a double must follow the real API, and when the API changes, the double changes with it. Better still, keep at least one integration test with no mocking, so the real API runs once and any lie in the double shows up immediately.
Lie two: mocking things that should not be mocked. The classic case is mocking your own code: a function under test calls a utility function you wrote yourself, and the AI helpfully replaces the utility too, so the test only proves that "the function called the mock, and the mock returned the hard-coded value." Deleting such a test would not lose a single bug, because it never tested your logic. The test is simple: if something is written by you, runs fast, and has no side effects, do not replace it. Doubles are for "other people's things, slow things, unstable things" — not for "your own code."
Lie three: double state leaking between tests. The mock in the first test returns "insufficient balance," the second test forgets to restore it and reuses the same mock, so the second test also reads "insufficient balance" and turns red for no reason — or worse, green for no reason. Both the Vitest and Jest documentation state cleanup as an iron rule: mockClear, mockReset, or mockRestore before or after each test, and the three do different jobs: mockClear only clears the call record, mockReset clears the implementation and return values too, and mockRestore returns a spy to the real implementation. A spy created with vi.spyOn must be returned with mockRestore, or the real function stays covered forever. AI-generated tests often write assertions and skip cleanup; the first thing to do when you take them over is to add cleanup to every test file.
Five anti-patterns
Anti-pattern one: mocking everything. The database, the network, the clock, the random numbers, and even your own pure functions, all replaced. In the end, the only real thing left is the test file itself. Remember: doubles are only for "other people's, slow, unstable" things; your own code runs for real.
Anti-pattern two: writing business logic inside a mock. To make the mock return "realistic-looking" data, a pile of conditional branches gets written into the mock factory. Nobody tests the logic inside a mock, nobody reviews it, and when it is wrong nobody knows. A mock only hands out fixed answers; if you need complex behavior, that is a sign to use a fake, or to split the logic out and test it separately.
Anti-pattern three: asserting only on the mock, never on the result. Every assertion in the test is "this mock was called three times," and not one checks "is the final total right?" The call record is a means, not the goal. The call count can be right and the result wrong, and the test should still turn red. Every test needs at least one assertion on the final result, not on the call books.
Anti-pattern four: referencing outside variables in a mock factory. Vitest's vi.mock is hoisted to the top of the file, and when the factory runs, outside variables do not exist yet. AI-generated tests love to write this code, and it fails at runtime with "variable not initialized." Either write the data inside the factory, or lift it with vi.hoisted().
Anti-pattern five: never cleaning doubles up, so state leaks between tests. Time pinned and never released, a global variable changed and never returned, a mock's return value left for the next test. Shuffle the test execution order and the results change with it. A test that is green today and red tomorrow, with nobody knowing why, is this pattern. Every test file needs cleanup: time, globals, and mocks, all given back.
Checklist: run through it before handing the tests in
Before writing a test: is this dependency stable, fast, and yours? Only replace it when it is unstable, slow, or not yours. Have you decided which layer to replace? Replace the boundary first (network, disk, clock) and let the logic run for real as much as possible. Is the double's answer simple enough? If one fixed value explains it, do not copy a whole real data table.
While writing the test: a stub only hands out fixed answers and holds no logic; use a mock only when you need to check the call books, and do not forget to assert the final result too; use a partial mock when only one export needs replacing, and keep the rest real; pin time with vi.setSystemTime and release it with vi.useRealTimers; never reference outside variables inside a vi.mock factory.
Before handing the test in: does every test file clean up (mockClear, mockReset, mockRestore, plus time and global resets)? Is there at least one test with no mocking, letting the real dependency run once? Run the suite once with the file order shuffled — is it still green? Change one number in a mock's return value — does the test turn red? That last one matters most: a test that can never turn red is no test at all. If changing a number does not turn it red, it is only testing the mock itself. Delete it and write it again.
Comments (0)
Sources
Related articles
On 11 November 2026, AWS open-sourced UAEF: adapters turn traces from LangGraph, LangChain, Strands and Bedrock AgentCore into one format, then 36 metrics across 7 dimensions score them, flagging regressions past 5%. The judge model is hardened too — scores must cite verbatim evidence, and never decide safety.
Flexbox lays things out in one direction at a time, and when it is done right, the nav bar, the card wall, and the cart rows all behave. This guide follows MDN's Basic concepts of flexbox, Aligning items in a flex container, and Controlling ratios of flex items along the main axis: the two axes, containers and items, direction and wrapping, free space, the three flex properties, alignment on both axes, and gaps and auto margins.
One order is one object: table, dishes, total, paid — all filed by label. This guide follows MDN's Working with objects, JSON, and Object references: object literals, dot vs bracket notation, adding and deleting properties, for...in with hasOwn, methods and this, getters and setters, references vs copies, Object.assign and friends, null-prototype objects, JSON's strict rules, and stringify and parse with their number-precision trap.