AutoGen Tutorial (TypeScript): mocking LLM calls in tests for beginners
This tutorial shows you how to replace real LLM calls with deterministic mocks in AutoGen TypeScript tests. You need this when your agent logic is ready, but you want fast, stable tests that do not depend on API latency, token costs, or flaky model output.
What You'll Need
- •Node.js 18+ and npm
- •A TypeScript project with
tsconfig.json - •
autogen-coreandautogen-extinstalled - •A test runner like
vitestorjest - •No API key is required for the mocked tests in this tutorial
- •Basic familiarity with AutoGen agents and message types
Step-by-Step
- •Install the packages you need for AutoGen and testing.
We are using the OpenAI chat client interface, but we will swap the real model out for a mock implementation in tests.
npm install autogen-core autogen-ext
npm install -D vitest typescript @types/node
- •Create a small agent wrapper that accepts any chat completion client.
This is the key design choice: your production code can use a real client, while your tests inject a fake one.
// src/askAgent.ts
import { AssistantAgent } from "autogen-ext";
import type { ChatCompletionClient } from "autogen-core";
export async function askAgent(
client: ChatCompletionClient,
input: string,
): Promise<string> {
const agent = new AssistantAgent({
name: "support-agent",
modelClient: client,
systemMessage: "You are a concise support assistant.",
});
const result = await agent.run([{ role: "user", content: input }]);
return result.messages.at(-1)?.content?.toString() ?? "";
}
- •Build a mock chat client for tests.
This mock implements the same interface your agent expects, but returns fixed responses instead of calling an external model.
// test/mockChatClient.ts
import type {
ChatCompletionClient,
CreateResult,
} from "autogen-core";
export class MockChatClient implements ChatCompletionClient {
constructor(private readonly replyText: string) {}
async create(): Promise<CreateResult> {
return {
content: [
{
type: "text",
text: this.replyText,
},
],
finish_reason: "stop",
usage: {
prompt_tokens: 0,
completion_tokens: 0,
},
};
}
close(): Promise<void> {
return Promise.resolve();
}
}
- •Write a test that injects the mock into your agent wrapper.
The test now checks your application logic, not the network or model behavior.
// test/askAgent.test.ts
import { describe, expect, it } from "vitest";
import { askAgent } from "../src/askAgent";
import { MockChatClient } from "./mockChatClient";
describe("askAgent", () => {
it("returns the mocked response", async () => {
const client = new MockChatClient("Approved. Your request is complete.");
const reply = await askAgent(client, "Please approve this request");
expect(reply).toContain("Approved");
});
});
- •Run the test suite and confirm it stays deterministic.
If you run it ten times, you should get the same output every time because there is no live LLM involved.
npx vitest run
Testing It
The first thing to verify is that your test passes without any network access. If it fails, check that your mock class matches the ChatCompletionClient shape expected by your AutoGen version.
Next, change the mocked reply text and confirm the assertion follows it exactly. That tells you your test is really using the injected mock instead of accidentally calling a real model.
If you want stronger coverage, add one test per branch in your agent logic and give each branch its own fixed mock response.
Next Steps
- •Add multiple mock responses to simulate retries or tool-use flows
- •Test structured outputs by mocking JSON content and parsing it in your service layer
- •Move from unit tests to integration tests with a real OpenAI client behind an environment flag
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit