Testing a Loop with a Scripted Model
Why This Matters
You cannot test a loop by hoping the real model takes the path you want. Script the model’s answers instead, and you can test every path, including the ugly ones, in milliseconds and for free. This is where testers have a real head start.
A scripted fake client
A fake that plays back a list of responses in order:
function scriptedClient(steps: Array<Partial<Message>>) {
const create = vi.fn();
for (const step of steps) create.mockResolvedValueOnce({ stop_reason: "end_turn", ...step });
return { client: { messages: { create } } as unknown as MessagesClient, create };
}
const toolUse = (id: string, name: string, input: object) => ({
stop_reason: "tool_use",
content: [{ type: "tool_use", id, name, input }],
});
The happy path
const { client, create } = scriptedClient([
toolUse("1", "get_test_history", { testId: "t-004" }),
toolUse("2", "read_log", { runId: "run-1042", testId: "t-004" }),
toolUse("3", "submit_verdict", { ...validTriage, testId: "t-004", category: "flaky" }),
]);
const verdict = await triageWithTools(client, run, failure);
expect(verdict.category).toBe("flaky");
expect(create).toHaveBeenCalledTimes(3);
The unhappy paths
These are the tests that matter:
| Scenario | What to assert |
|---|---|
| A tool returns an error | The next request contains a tool_result with is_error: true and your message |
| The model asks for an unknown tool | The loop answers with an error result instead of crashing |
| The model never stops | The loop ends at the step limit and reports “not triaged” |
The model calls create_issue | A proposal is recorded; the tracker is never called |
| Two tool calls in one turn | Both get a result, with matching ids, in one message |
Assert on what you send back
The most valuable assertions are on the requests your code sends, not only on the final verdict:
const third = create.mock.calls[2][0].messages.at(-1);
expect(third.content[0]).toMatchObject({ type: "tool_result", tool_use_id: "2", is_error: true });
That is how you prove the loop handles errors correctly, regardless of what any real model would do.
Where scripted tests end
Scripted tests check your code: the loop, the tools, the limits, the gates. They say nothing about whether the model makes good choices. That is what the golden set and the eval from module 3 are for. You need both.
Exercise
Write the five unhappy-path tests from the table. They should all run in under a second, without an API key.
Compare with solution/lesson-31-mcp-server, which covers lessons 24–31 (see docs/exercises.md, module 4).