Claude API Unit Testing: Mocking Strategies That Work
Claude API unit testing: mocking strategies that work
If you're searching for "claude api unit testing mocking strategies," you probably have one specific problem: your test suite is either too slow (hitting the real API), too brittle (breaking on every prompt tweak), or too fake (mocking so much it tests nothing). The fix is a layered approach — mock at the network boundary for unit tests, use recorded fixtures for regression tests, and reserve a small number of real API calls for integration/contract tests that run less often.
This article walks through concrete strategies: how to structure your code so Claude calls are mockable, what to mock versus what to record, how to handle streaming and tool-use responses, and how to avoid the two classic failure modes — tests that pass against a mock but fail in production, and tests so tightly coupled to response shape that they break on harmless API changes.
Why mocking Claude is harder than mocking a typical REST call
A plain REST endpoint usually returns a fixed shape. Claude responses vary by:
- Streaming vs non-streaming — different event sequences (
message_start,content_block_delta,message_stop, etc.) - Tool use — the model can return
tool_useblocks instead of plain text, and your code has to branch on that - Non-determinism — the same prompt can produce different wording, so you can't assert on exact text
- Token/usage metadata — present in every response, often ignored by naive tests until a billing bug appears
Your mocking strategy has to account for all of these without turning every test into a 200-line fixture file.
Strategy 1: isolate the API call behind a thin client
Don't scatter fetch("https://api.../v1/messages") calls through your business logic. Wrap them in a single module:
// claudeClient.js
export async function sendMessage({ model, messages, tools }) {
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ model, messages, tools }),
});
return res.json();
}
Now every other function depends on sendMessage, not on fetch or an SDK instance. This single seam is what makes everything below possible — you mock sendMessage, not the HTTP layer, in most unit tests.
Strategy 2: unit test with hand-written response fixtures
For pure logic tests (parsing a response, extracting a tool call, formatting output for a user), mock the client function directly and return a minimal, hand-crafted object — not a full recorded response. Minimal fixtures keep tests readable and resistant to unrelated field changes.
import { jest } from "@jest/globals";
import * as client from "./claudeClient.js";
import { summarizeTicket } from "./ticketSummarizer.js";
test("extracts summary text from a Claude response", async () => {
jest.spyOn(client, "sendMessage").mockResolvedValue({
content: [{ type: "text", text: "Customer wants a refund." }],
usage: { input_tokens: 120, output_tokens: 8 },
});
const result = await summarizeTicket({ ticketId: "123" });
expect(result.summary).toBe("Customer wants a refund.");
});
Only include the fields your function actually reads. This is the opposite of copy-pasting a full API response — resist that urge, because it makes every test depend on every field.
Strategy 3: record real responses for regression fixtures
For higher-level tests (an end-to-end "process this webhook payload" flow), record one real response per scenario and replay it. This catches regressions when the model's actual output format shifts — e.g., a tool call structure you didn't anticipate.
// fixtures/refund-request.json — captured once from a real call
{
"id": "msg_01...",
"content": [
{ "type": "tool_use", "name": "issue_refund", "input": { "amount": 42.5 } }
],
"stop_reason": "tool_use",
"usage": { "input_tokens": 340, "output_tokens": 55 }
}
Store these fixtures in version control, label them by scenario (refund, escalation, no-tool-needed), and regenerate them periodically — ideally via a scripted job that calls the real API and overwrites the fixture, rather than manual edits. Manual edits drift from reality fast.
Strategy 4: mock streaming without reimplementing SSE parsing
Streaming is the part most teams get wrong — they either skip testing it entirely or build an elaborate fake SSE server. A simpler approach: mock at the level of your stream-consuming function, feeding it an async iterator of pre-built chunks.
async function* fakeStream() {
yield { type: "content_block_delta", delta: { text: "Hel" } };
yield { type: "content_block_delta", delta: { text: "lo" } };
yield { type: "message_stop" };
}
test("accumulates streamed text", async () => {
const text = await collectStreamedText(fakeStream());
expect(text).toBe("Hello");
});
This tests your accumulation/consumption logic without touching the network at all. If you're implementing streaming against SubToAPI, the event shapes are documented at /docs/streaming — mirror those shapes in your fixtures so your mocks stay honest.
Strategy 5: contract tests as the safety net
Unit tests with fixtures will happily pass even if the real API changes its response shape underneath you. Run a small, separate suite — a handful of tests, not hundreds — that hits the real endpoint with cheap, short prompts and asserts on structure (fields present, types correct) rather than exact content. Run this suite in CI on a schedule (nightly) rather than on every commit, since it costs tokens and adds latency.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-3-5-sonnet",
"max_tokens": 16,
"messages": [{"role": "user", "content": "Reply with the word OK."}]
}'
If this breaks, your mocks are probably stale too — treat a contract test failure as a signal to regenerate fixtures, not just a bug in your app. Having a single API surface (as with SubToAPI's /docs/messages endpoint) makes this easier, since you're testing one contract instead of juggling SDK-specific response objects per provider.
Strategy 6: test tool-use branching explicitly
Tool use is where mocking pays off most, because triggering a specific tool call reliably from a real model is slow and sometimes inconsistent. Mock the response to force each branch:
test("routes to refund handler on tool_use", async () => {
jest.spyOn(client, "sendMessage").mockResolvedValue({
content: [{ type: "tool_use", name: "issue_refund", input: { amount: 10 } }],
stop_reason: "tool_use",
});
const action = await handleModelResponse(await client.sendMessage({}));
expect(action.type).toBe("refund");
expect(action.amount).toBe(10);
});
Write one fixture per tool and one for "no tool, plain text" — that's usually enough coverage for the routing logic. For tool schema details, see /docs/tools.
Putting it together
A practical test pyramid for Claude integrations looks like:
- Many unit tests mocking the client function with minimal fixtures (fast, run on every commit)
- Some fixture-replay tests covering streaming and tool-use scenarios (fast, run on every commit)
- Few contract tests against the real API (slower, scheduled or pre-release)
If you're building against SubToAPI, this pattern works the same way whether you're calling it directly with fetch/curl or through a thin wrapper — the /docs/quickstart guide shows the request/response shapes you'll want to mirror in your fixtures, and a free trial via /signup is enough to record a few real fixtures before you lock down your mocks.
Questions
Should I mock the Claude SDK or the HTTP layer? Mock at the highest seam that still exercises your logic — usually a thin client function you wrote, not fetch or the SDK internals. This keeps tests stable across SDK version bumps.
How often should I regenerate fixtures from real responses? Regenerate on a schedule (e.g., monthly) or whenever a contract test fails, via a script rather than manual edits, so fixtures stay close to real response shapes without constant maintenance.
Can I unit test streaming without a real connection? Yes — feed your stream-consumer function a hand-built async iterator of chunk objects matching the documented event shapes; you're testing your accumulation logic, not the transport.