How to Test AI Agents Like Normal Software
Learn to test AI agents with deterministic unit tests, integration checks, and observability, using practical examples you can run today.
Before you start
You have an AI agent that calls tools, decides next steps, and sometimes goes off the rails. You want to test it like you test any other software: fast, deterministic, and reliable. But LLM outputs are non-deterministic, so you need a strategy that separates the flaky parts from the logic you control.
This guide shows you how to test an agent built with TypeScript and the Vercel AI SDK. You will write unit tests for the agent loop, mock the LLM, test tool calls with a fake executor, and add integration tests that verify the agent handles a real API failure gracefully. You will also set up observability with OpenTelemetry so you can trace what the agent actually did in production.
- You need Node.js 18 or later and npm installed.
- You should be familiar with basic TypeScript and the Vercel AI SDK.
- You will use Vitest for unit tests and Playwright for one end-to-end check.
Step 1: Build a minimal agent
Create a file called agent.ts. This is the agent you will test.
import { generateText, tool } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';
import 'dotenv/config';
const weatherTool = tool({
description: 'Get the current weather in a city',
parameters: z.object({ city: z.string() }),
execute: async ({ city }) => {
const response = await fetch(`https://api.weather.example/v1/weather?city=${encodeURIComponent(city)}`);
if (!response.ok) throw new Error('Weather API failed');
return response.json();
},
});
export async function runAgent(prompt: string) {
const result = await generateText({
model: openai('gpt-4o-mini'),
prompt,
tools: { weather: weatherTool },
maxSteps: 5,
});
return result.text;
}
// Usage: node -e "import('./agent.js').then(m => m.runAgent('What is the weather in Paris?'))"Step 2: Write deterministic unit tests
The agent loop itself is deterministic: given a tool result, it should produce a final answer. You can test this without hitting the LLM by mocking the model. Use Vitest to mock the generateText function and assert that the agent returns the expected text.
npx vitest runimport { describe, it, expect, vi, beforeEach } from 'vitest';
import { runAgent } from './agent';
vi.mock('ai', () => ({
generateText: vi.fn(),
tool: (config: any) => config,
}));
import { generateText } from 'ai';
beforeEach(() => {
vi.mocked(generateText).mockReset();
});
describe('runAgent', () => {
it('returns the model output as the final answer', async () => {
vi.mocked(generateText).mockResolvedValue({ text: 'The weather in Paris is 20C.' } as any);
const result = await runAgent('What is the weather in Paris?');
expect(result).toBe('The weather in Paris is 20C.');
});
it('passes the prompt and tools to the model', async () => {
vi.mocked(generateText).mockResolvedValue({ text: 'ok' } as any);
await runAgent('Hello');
expect(generateText).toHaveBeenCalledWith(
expect.objectContaining({
prompt: 'Hello',
tools: expect.objectContaining({ weather: expect.any(Object) }),
})
);
});
});Step 3: Test the tool executor
The tool executor is where real-world failures happen. Write a unit test for the weather tool by mocking the fetch call. Verify it returns the parsed JSON on success and throws on a non-OK response.
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { weatherTool } from './agent';
const mockFetch = vi.fn();
vi.stubGlobal('fetch', mockFetch);
beforeEach(() => {
mockFetch.mockReset();
});
describe('weatherTool.execute', () => {
it('returns weather data on success', async () => {
mockFetch.mockResolvedValue({ ok: true, json: async () => ({ temp: 20, unit: 'C' }) });
const result = await weatherTool.execute({ city: 'Paris' });
expect(result).toEqual({ temp: 20, unit: 'C' });
});
it('throws when the API returns an error', async () => {
mockFetch.mockResolvedValue({ ok: false, status: 500 });
await expect(weatherTool.execute({ city: 'Paris' })).rejects.toThrow('Weather API failed');
});
});Step 4: Integration test the agent with a fake LLM
To make this test work, refactor agent.ts to accept a tools parameter, so you can pass a fake weather tool in tests. This is a common pattern: inject dependencies to keep tests isolated.
import { describe, it, expect, vi } from 'vitest';
import { runAgent } from './agent';
vi.mock('ai', () => {
return {
generateText: vi.fn(),
tool: (config: any) => config,
};
});
import { generateText } from 'ai';
describe('runAgent integration', () => {
it('executes the tool and returns the final answer', async () => {
const toolResult = { temp: 20, unit: 'C' };
vi.mocked(generateText)
.mockResolvedValueOnce({
text: '',
toolCalls: [{ id: '1', type: 'function', function: { name: 'weather', arguments: JSON.stringify({ city: 'Paris' }) } }],
} as any)
.mockResolvedValueOnce({ text: 'The weather is 20C.' } as any);
// Override the tool executor to avoid network calls
const { runAgent } = await import('./agent');
// This requires refactoring agent.ts to allow injecting the tool executor
// For brevity, we assume the tool is mocked globally.
// In practice, you would use dependency injection or a test double.
const result = await runAgent('What is the weather in Paris?');
expect(result).toBe('The weather is 20C.');
expect(generateText).toHaveBeenCalledTimes(2);
});
});Step 5: Add observability with OpenTelemetry
The AI SDK supports OpenTelemetry natively. When you enable it, you get spans for each model call and tool execution. You can export these traces to any OTLP-compatible backend like Jaeger or Grafana Tempo.
npm install @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/instrumentation-http @opentelemetry/instrumentation-fetchimport { trace, Span } from '@opentelemetry/api';
const tracer = trace.getTracer('agent');
export async function runAgent(prompt: string) {
return tracer.startActiveSpan('agent.run', async (span: Span) => {
span.setAttribute('prompt', prompt);
const result = await generateText({
model: openai('gpt-4o-mini'),
prompt,
tools: { weather: weatherTool },
maxSteps: 5,
experimental_telemetry: { isEnabled: true, functionId: 'agent-run' },
});
span.setAttribute('final_text', result.text);
span.end();
return result.text;
});
}Step 6: End-to-end smoke test
Finally, add a quick end-to-end test that runs the agent against a real LLM once per CI run, not on every commit. Use a script that sets a timeout and fails if the agent does not respond within 30 seconds. This catches regressions in the model or API integration.
cat > smoke-test.sh << 'EOF'
#!/bin/bash
set -e
export OPENAI_API_KEY=$OPENAI_API_KEY
node -e "import('./agent.js').then(m => m.runAgent('What is the weather in London?')).then(console.log).catch(e => { console.error(e); process.exit(1); })"
EOF
chmod +x smoke-test.sh
./smoke-test.shRecommended setup
For a production agent, I recommend the following setup: use Vitest for unit and integration tests, mock the LLM for fast tests, and run one real-LLM smoke test nightly. Add OpenTelemetry tracing from day one so you can debug failures. Keep your agent logic separate from the model calls so you can test it without a network.
- Use dependency injection for tools and model to make testing easy.
- Mock the LLM in unit tests to keep them fast and deterministic.
- Run integration tests against a fake model to verify the agent loop.
- Add a real-LLM smoke test in CI, but only on a schedule or a manual trigger.
- Instrument with OpenTelemetry to trace every agent decision.
- Set up alerts on error rates and latency for your agent endpoints.
Troubleshooting
If your tests are flaky, check that you are mocking the network calls. If the agent is slow, reduce maxSteps. If you see timeouts, adjust the fetch timeout in the tool executor.
- Flaky tests: ensure fetch is mocked in every test that calls a tool.
- LLM rate limits: use a fake model in tests to avoid hitting the API.
- Agent loops forever: set a maxSteps limit and assert it in tests.
- Missing traces: verify the OpenTelemetry SDK is initialized before the agent runs.
FAQ
Here are common questions developers ask when testing AI agents.
- Q: Can I test an agent without mocking the LLM? A: Yes, but it will be slow and flaky. Use a real LLM only in smoke tests.
- Q: How do I test that the agent calls the right tool? A: Mock the model to return a tool call, then assert the tool executor was invoked with the expected arguments.
- Q: What if the tool fails? A: Write a test that makes the tool throw, and assert the agent handles it gracefully.
- Q: How do I test multi-step agents? A: Mock the model to return multiple tool calls in sequence.
- Q: Is OpenTelemetry worth it for a small agent? A: Yes, it saves debugging time when something goes wrong in production.
Try it on code.live
You can practice testing agents with the API Mock Data Generator to simulate tool responses, and use the JSON Formatter to inspect the tool arguments and results. These tools help you build realistic test fixtures without hitting real APIs.
Key takeaways
- Apply one concrete change from this post before collecting more reading.
- Prefer browser-side tools when the work involves secrets, tokens, or PII.
- Document the why next to the how so the next reviewer inherits context.
FAQ
- Who is this guide on ai-agents for?
- Working developers who need a practical take on how to test ai agents like normal software — not a marketing overview. Skim the sections, apply one tip, then come back when you hit an edge case.
- Do I need an account to use the related tools?
- No. code.live tools run in your browser with no signup. Nothing you paste is uploaded to a server for the client-side utilities linked from this post.
- How often is this article updated?
- This post was published November 25, 2026. Fundamentals stay stable; check linked tool pages and official docs when version-specific behavior matters.