Topic 1 of 4 · 4 min read
Mocking the model provider in unit tests
Goal: Write a unit test that replaces the provider with a mock returning a fixed response, stream, tool call or error.
A unit test for code that calls a model should never call a model: put a fake provider at one seam and make it return exactly what the test needs. Real calls are slow, cost money, need a key and give a different answer each run. A test built on them tells you little.
Check yourself · 1 of 3
Why should a unit test of your summarising function not call a real model?
Why it matters
Your code around the model is ordinary code: it builds a request, parses the reply, runs tool calls, handles errors. Most bugs live there, not in the model. A mock lets you test all of it in milliseconds, offline, in CI, with no key.
Where to put the seam
Pick one place and keep it small.
- Your own wrapper. Write one function such as
complete(messages)that the rest of the app calls. In tests, pass a fake. This is the easiest to maintain and keeps the vendor SDK out of most files. - The SDK client. Inject the client into your class, or mock the module with Vitest or Jest (
vi.mock) orunittest.mockin Python. Libraries such as the AI SDK ship mock models for this. - The HTTP layer. Tools like Mock Service Worker intercept the request, so the real SDK code runs against a fake server. It catches more, and costs more setup.
What the mock should return
Cover each shape your code handles: plain text, a streamed reply in several chunks, a tool call with arguments, and an error. Use the real response shape from the provider docs, including fields you do not read today. A hand-trimmed fake that omits usage or stop_reason hides bugs.
Assert on two things: what your code sent (model name, system prompt, tool list, max tokens) and what it did with the reply.
Before and after
// Before: hits the network, flaky, costs money
test("summarises", async () => {
const out = await summarise("long text");
expect(out).toContain("summary");
});
// After: fake provider, exact input and output
test("summarises", async () => {
const complete = vi.fn().mockResolvedValue({ text: "Two sentences.", stopReason: "end_turn" });
const out = await summarise("long text", { complete });
expect(out).toBe("Two sentences.");
expect(complete).toHaveBeenCalledWith(expect.objectContaining({ maxTokens: 300 }));
});
What goes wrong
- A mock that is too kind. It always returns clean text, so the error and empty-reply paths are never run.
- Asserting on the model's words. A test that checks wording from a real model fails on the next release. With a mock you control the words; test your logic.
- Mocking your own code. If the mock replaces the function under test, the test proves nothing.
- A mock that drifts. The provider adds a field or renames one and the fake stays old. Check mocks against a recorded real response now and then.
Examples
Faking a tool call
const complete = vi.fn().mockResolvedValue({
stopReason: "tool_use",
toolCalls: [{ id: "t1", name: "get_order", args: { id: "A-1042" } }],
});
The test checks that the app runs get_order with A-1042, sends the result back and returns the final text. No model was needed to prove the loop works.
Faking a stream
async function* fakeStream() {
yield { type: "text", text: "Hel" };
yield { type: "text", text: "lo" };
yield { type: "done" };
}
The UI test asserts that "Hello" appears after the last chunk, and that the loading state clears on done.
Key points
- Put the fake at one seam: your own wrapper, the SDK client or the HTTP layer.
- Mock every reply shape your code handles: text, stream chunks, tool calls and errors.
- Use the provider's real response shape, including fields you do not read yet.
- Assert on what your code sent and what it did with the reply, not on model wording.
- Mocks test your logic; they cannot tell you whether the real provider still behaves this way.
Common mistakes
- Returning only happy-path text from the mock, so error and empty-reply handling is never exercised.
- Writing a trimmed fake response that leaves out fields the real API sends, such as usage or stop reason.
- Asserting on exact model wording instead of on the request sent and the logic that follows.
- Mocking the very function the test claims to check.
Check yourself · 2 of 3
A mock model always returns clean text. Which code path is most likely to go untested?
Check yourself · 3 of 3
Your test mocks the SDK with a fake reply that has only a text field. The real API also sends stop reason and usage. What is the risk?
Practice items, not counted towards your mastery.
Start here
- AI SDK Core: testing (opens in a new tab)DocsFree
Mock language models and test helpers that return fixed text, streams and errors without network calls.
- Mock Service Worker documentation (opens in a new tab)ToolFree
Intercepting HTTP requests at the network layer, so the real SDK runs against a fake server.
- VCR.py documentation (opens in a new tab)ToolFree
Record modes, header filtering and replay for HTTP cassettes in Python tests.
More for this topic
- Mocking (Vitest) (opens in a new tab)DocsFree
Module, function and timer mocks used to replace an SDK client in unit tests.