How do you test code that calls an LLM?

Learning path, stage 5 of 5: Shipping to production · question 9 of 10

Split it into layers. Unit-test your own logic with the LLM mocked: prompt building, parsing, tool dispatch, error handling. Run a smaller set of integration tests against the real API for contract checks. Measure quality with evals, which check properties and pass rates rather than exact strings. LLM output varies, so assert on structure and behaviour, not on wording.

The layers

  • Unit (mocked, fast, in every CI run):
    • Prompt templates render correctly.
    • Parsers handle malformed output.
    • The agent loop handles tool_use, errors and step limits.
    • Retries happen only for retryable errors.
  • Contract (real API, few cases): the schema still validates, the tools are still called, auth and config work.
  • Evals (real API, many cases, nightly or on prompt changes): pass rates against a threshold, tracked over time.

Techniques

  • Record and replay fixtures of real responses for deterministic tests.
  • Property assertions: valid JSON, category in the enum, mentions the order ID, under N words, no PII.
  • Snapshot prompts, not outputs: catch accidental prompt changes in code review.
  • Separate flaky checks (quality) from blocking ones (correctness of your code).

Sources

Code example

tsx
1// Unit-testing an LLM feature with an injected, mocked client (Vitest).
2import { describe, it, expect, vi } from "vitest";
3
4type Llm = (prompt: string) => Promise<string>;
5
6// code under test: depends on an injected LLM function
7export async function classify(ticket: string, llm: Llm) {
8 const raw = await llm(`Classify as bug|question|other. JSON {"label":...}\n${ticket}`);
9 try {
10 const { label } = JSON.parse(raw);
11 return ["bug", "question", "other"].includes(label) ? label : "other";
12 } catch {
13 return "other"; // malformed output must not crash
14 }
15}
16
17describe("classify", () => {
18 it("parses a valid label", async () => {
19 const llm = vi.fn().mockResolvedValue('{"label":"bug"}');
20 expect(await classify("app crashes", llm)).toBe("bug");
21 expect(llm.mock.calls[0][0]).toContain("app crashes"); // prompt includes input
22 });
23
24 it("falls back on malformed or unexpected output", async () => {
25 expect(await classify("x", vi.fn().mockResolvedValue("Sure! It's a bug"))).toBe("other");
26 expect(await classify("x", vi.fn().mockResolvedValue('{"label":"urgent"}'))).toBe("other");
27 });
28});

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod @opentelemetry/api vitest, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app