---
title: "Test a Voice Agent in TypeScript with Simulated Callers"
description: "Unit tests for the tools and handoffs of a voice agent, simulated callers played by a model and scored by a judge, and audio tests for turn taking and interruptions, all in node:test, vitest or jest."
url: "https://micdrop.dev/blog/testing-voice-agent-simulated-callers"
---

# Test a TypeScript voice agent with simulated calls and simulated callers

Unit tests for the tools and handoffs of a voice agent, simulated callers played by a model and scored by a judge, and audio tests for turn taking and interruptions, all in node:test, vitest or jest.

November 29, 2026

[Godefroy de Compreignac](https://github.com/Godefroy)

Key takeaways

*   A voice agent fails in three places: the wiring around the model (tools, handoffs, hang up), the conversation the model holds, and the audio (pauses, interruptions). Each one gets its own kind of test.
*   \`@micdrop/testing\` runs your real Micdrop config in a test: a text simulation with fakes in place of the speech providers, a simulated caller played by a model or a script, and an audio simulation through your real speech to text and turn detection.
*   Tests with a scripted agent run offline in milliseconds, so they fit every push. Tests that call a model answer differently each run, so they run on demand and count as a success rate.
*   The assertions throw a standard \`AssertionError\`, so the same tests run in node:test, vitest or jest.

A voice agent passes the demo, then a real caller asks for a refund on the wrong order, gets transferred to billing for a delivery question, or is cut off in the middle of a sentence. Each of those failures has a place where a test catches it before a release. This tutorial writes those tests for a TypeScript voice agent, from the fastest to the most faithful, with [Micdrop](/), the open source library this site publishes, and its `@micdrop/testing` package.

The finished project is the support agent of a small shop. It looks orders up, refunds the lost ones, transfers invoice questions to a billing agent and hangs up when the caller says goodbye. The same code lives in the [testing example](https://github.com/Godefroy/micdrop/tree/main/examples/testing) of the repository.

## Three things to test, three kinds of tests

What fails

Example

Test

Speed and cost

The wiring around the model

A tool gets the wrong parameters, a handoff points to the wrong agent

Text simulation with a scripted agent

Offline, milliseconds

The conversation

The agent refunds without asking, or never gives the amount

Simulated caller and judge, played by models

Calls your model, seconds per conversation

The audio

A pause cuts a sentence in two, the agent keeps talking over the user

Audio simulation through your real speech to text and VAD

Real time, calls your speech to text

The first kind runs on every push. The second runs before a release, or every night. The third runs when you change the turn detection or the speech to text.

## Set up the project

```bash
mkdir support-agent && cd support-agent
npm init -y
npm pkg set type=module
npm install @micdrop/server @micdrop/ai-sdk @ai-sdk/openai ai zod
npm install -D @micdrop/testing tsx typescript @types/node
npm pkg set scripts.test="node --import tsx --test tests/agent.test.ts"
npm pkg set scripts.test:live="node --env-file=.env --import tsx --test tests/agent.live.test.ts"
```

The tests use the runner built into Node. The same files run in vitest or jest by importing `describe` and `it` from there.

## Build the config in one place

The kit starts a server with the config your app gives it. Build that config in a function, without its speech to text and voice, so the app and the tests share it. The model is a parameter, so a test can pass another one:

`src/agent.ts`

```typescript
import { AiSdkAgent } from '@micdrop/ai-sdk'
import {
  endCallTool,
  handoffTool,
  MicdropPipelineConfig,
  Tool,
} from '@micdrop/server'
import type { LanguageModel } from 'ai'
import { z } from 'zod'

// A real app reads them from its database
const ORDERS: Record<string, { status: string; total: number }> = {
  '42': { status: 'shipped', total: 59 },
  '43': { status: 'lost', total: 120 },
}

const orderInput = z.object({ orderId: z.string() })

export const lookupOrder: Tool<typeof orderInput> = {
  name: 'lookup_order',
  description: 'Find an order by its number',
  inputSchema: orderInput,
  execute: ({ orderId }) => ORDERS[orderId] ?? { error: 'No such order' },
}

export const refundOrder: Tool<typeof orderInput> = {
  name: 'refund_order',
  description: 'Refund a lost order, once the customer agreed',
  inputSchema: orderInput,
  execute: ({ orderId }) =>
    ORDERS[orderId]?.status === 'lost'
      ? { refunded: ORDERS[orderId].total }
      : { error: 'Only a lost order can be refunded' },
}

// A voice needs speed: reasoning off
const providerOptions = { openai: { reasoningEffort: 'none' as const } }

export function createBillingAgent(model: LanguageModel) {
  return new AiSdkAgent({
    model,
    providerOptions,
    systemPrompt:
      'You handle the invoices and payments of the shop. Answer in one or two short spoken sentences.',
    tools: [endCallTool()],
  })
}

export function createCallConfig(model: LanguageModel): MicdropPipelineConfig {
  return {
    agent: new AiSdkAgent({
      model,
      providerOptions,
      systemPrompt: [
        'You are the phone support of a small shop. Answer in one or two short spoken sentences.',
        'Look orders up with lookup_order. Refund a lost order with refund_order once the customer agrees.',
        'Transfer questions about invoices and payments to billing.',
        'End the call when the customer says goodbye.',
      ].join('\n'),
      tools: [
        lookupOrder,
        refundOrder,
        handoffTool({ name: 'billing', to: () => createBillingAgent(model) }),
        endCallTool(),
      ],
    }),
    firstMessage: 'Hello, this is the shop support. How can I help?',
  }
}
```

The server of the app adds the speech providers around it:

`src/server.ts`

```typescript
import { openai } from '@ai-sdk/openai'
import { OpenaiSTT, OpenaiTTS } from '@micdrop/openai'
import { MicdropServer } from '@micdrop/server'
import { WebSocketServer } from 'ws'
import { createCallConfig } from './agent'

const apiKey = process.env.OPENAI_API_KEY || ''

new WebSocketServer({ port: 8081 }).on('connection', (socket) => {
  new MicdropServer(socket, {
    ...createCallConfig(openai('gpt-5.2')),
    stt: new OpenaiSTT({ apiKey }),
    tts: new OpenaiTTS({ apiKey, voice: 'alloy' }),
  })
})
```

## Test the wiring offline

A test that knows exactly what the model says checks everything around it: the parameters of the tools, their outputs, the handoffs and the end of the call. `ScriptedAgent` stands in for the model and runs your real tools, the way a model would call them. Each answer is a text, or a list of steps.

`TestCall.start()` starts the call with fakes in place of the speech to text and the voice, and waits for the first message. Each `say()` is a turn of the user and resolves once the agent is done answering, tools included.

`tests/agent.test.ts`

```typescript
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { endCallTool } from '@micdrop/server'
import {
  expectAnswer,
  expectEndCall,
  expectLatency,
  expectNoToolCall,
  expectPassed,
  expectToolCall,
  ScriptedAgent,
  scriptedCaller,
  simulateConversation,
  TestCall,
} from '@micdrop/testing'
import { lookupOrder, refundOrder } from '../src/agent'

const tools = [lookupOrder, refundOrder, endCallTool()]

describe('Support agent, offline', () => {
  it('looks an order up and says its status', async () => {
    const call = await TestCall.start({
      agent: new ScriptedAgent(
        [
          [
            { tool: 'lookup_order', args: { orderId: '42' } },
            { say: 'Your order 42 has shipped.' },
          ],
        ],
        { tools }
      ),
      firstMessage: 'Hello, how can I help?',
    })
    expectAnswer(call.opening, 'how can I help')

    const turn = await call.say('Where is my order 42?')
    const lookup = expectToolCall(turn, 'lookup_order', { orderId: '42' })
    assert.deepEqual(lookup.output, { status: 'shipped', total: 59 })
    expectAnswer(turn, 'shipped')
    expectNoToolCall(turn, 'refund_order')

    const metrics = await call.waitForMetrics(turn)
    expectLatency(metrics, { llm: 500 })
    await call.end()
  })

  it('refuses to refund an order that was not lost', async () => {
    const call = await TestCall.start({
      agent: new ScriptedAgent(
        [
          [
            { tool: 'refund_order', args: { orderId: '42' } },
            { say: 'Sorry, this order cannot be refunded.' },
          ],
        ],
        { tools }
      ),
    })
    const turn = await call.say('Refund my order 42')
    const refund = expectToolCall(turn, 'refund_order')
    assert.deepEqual(refund.output, {
      error: 'Only a lost order can be refunded',
    })
    await call.end()
  })

  it('follows a whole conversation to its goodbye', async () => {
    const result = await simulateConversation({
      config: () => ({
        agent: new ScriptedAgent(
          [
            [
              { tool: 'lookup_order', args: { orderId: '43' } },
              { say: 'Your order 43 was lost. Shall I refund it?' },
            ],
            [
              { tool: 'refund_order', args: { orderId: '43' } },
              { say: 'Done, 120 dollars are refunded.' },
            ],
            [{ say: 'Goodbye!' }, { tool: 'end_call' }],
          ],
          { tools }
        ),
      }),
      caller: scriptedCaller([
        'My order 43 never came',
        { say: 'Yes please', after: 'refund' },
        'Thanks, goodbye',
      ]),
      assertions: (call) => {
        expectToolCall(call, 'refund_order', { orderId: '43' })
        expectEndCall(call)
      },
    })
    expectPassed(result)
    assert.equal(result.endedBy, 'agent')
  })
})
```

```bash
npm test
```

The whole file runs in well under a second, with no network. A step can also `wait` some milliseconds, report `usage`, `throw` or `hang`, to check how your app behaves when the model is slow or fails.

To keep your real `AiSdkAgent` and replace only its model, pass `createCallConfig()` a mock model of the AI SDK. The testing example does it with `MockLanguageModelV4`, which also covers the handoff to billing offline.

### What the assertions check

Assertion

Passes when

`expectToolCall(record, name, parameters?)`

The tool was called, with parameters that match. Returns the call, with its `output`

`expectNoToolCall(record, name?)`

The tool was not called, or no tool at all

`expectToolCallOrder(record, names)`

The tools were called in this order

`expectHandoff(record, to?)` and `expectNoHandoff(record)`

The call was handed over, or stayed with its agent

`expectEndCall(record)` and `expectNoEndCall(record)`

The agent ended the call, or kept it open

`expectAnswer(record, matcher)` and `expectNoAnswer(record, matcher?)`

The answer matches a text, a `RegExp` or a predicate, or none does

`expectSkipped(turn)`

The agent said nothing back

`expectLatency(metrics, limits)`

The turn or the call answered within the limits

Each assertion takes a turn, a call or the result of a simulated conversation, and prints the conversation when it fails. Parameters match key by key, and a value can be a `RegExp` or a predicate.

## Let a model play the caller

The offline tests prove the wiring. They say nothing about how your model behaves with a real person, who explains things in the wrong order, gets impatient, or changes their mind. A simulated caller plays that person, and a judge reads the conversation afterwards.

`simulateConversation()` lets the caller talk to your agent until one of them hangs up, or until `maxTurns`. `@micdrop/testing/ai-sdk` builds the caller and the judge with any model of the [AI SDK](https://ai-sdk.dev):

`tests/agent.live.test.ts`

```typescript
import { describe, it } from 'node:test'
import { openai } from '@ai-sdk/openai'
import {
  expectHandoff,
  expectPassed,
  expectToolCall,
  simulateConversation,
  TestCall,
} from '@micdrop/testing'
import { aiSdkCaller, aiSdkJudge } from '@micdrop/testing/ai-sdk'
import { createCallConfig } from '../src/agent'

const model = openai('gpt-5.2')
const tester = openai('gpt-5-mini')

describe('Support agent, live', { skip: !process.env.OPENAI_API_KEY }, () => {
  it('transfers invoice questions to billing', async () => {
    const call = await TestCall.start(createCallConfig(model))
    const turn = await call.say('I need a copy of my last invoice, please.')
    expectHandoff(turn, 'billing')
    await call.end()
  })

  it('refunds a lost order for an impatient customer', async () => {
    const result = await simulateConversation({
      config: () => createCallConfig(model),
      caller: aiSdkCaller({
        model: tester,
        instructions:
          'You are Sam, a bit impatient. Your order 43 never arrived and you want your money back. Hang up once the refund is confirmed.',
      }),
      maxTurns: 8,
      assertions: (call) => {
        expectToolCall(call, 'lookup_order', { orderId: '43' })
        expectToolCall(call, 'refund_order', { orderId: '43' })
      },
      judge: aiSdkJudge({
        model: tester,
        criteria: [
          'The assistant asked before refunding',
          'The assistant told the amount refunded',
          'Every answer of the assistant is short enough to be spoken',
        ],
      }),
    })
    expectPassed(result)
  })
})
```

```bash
echo "OPENAI_API_KEY=sk-..." > .env
npm run test:live
```

The assertions check facts the code can see: the refund went to order 43. The judge checks what only a reader can: the assistant asked first, and kept its answers short enough for the ear. `result` holds `passed`, `endedBy`, the `transcript` and the `verdicts` of each check by name, which is what you print when a run fails.

Give `config` a function, so each conversation starts with fresh agents. A judge can also be a plain function returning `{ pass, reason }`, for rules that need no model, such as a maximum length per answer.

### Count successes rather than a single pass

A model answers differently from one run to the next, so one passing conversation proves little and one failing conversation may be bad luck. Run the conversations that matter several times and check a rate, in the same live file with `assert` imported from `node:assert/strict`:

```typescript
it('refunds a lost order in most conversations', async () => {
  const runs = 5
  let passed = 0
  for (let i = 0; i < runs; i++) {
    const result = await simulateConversation({
      config: () => createCallConfig(model),
      caller: aiSdkCaller({
        model: tester,
        instructions: 'Your order 43 never arrived and you want a refund.',
      }),
      maxTurns: 8,
      assertions: (call) => expectToolCall(call, 'refund_order', { orderId: '43' }),
    })
    if (result.passed) passed++
    else console.log(result.transcript)
  }
  assert.ok(passed >= 4, `${passed} of ${runs} conversations passed`)
})
```

The rate becomes the number to track when you change the prompt or the model: a new prompt that moves it from 4 out of 5 to 5 out of 5 is a real gain.

## Check the latency in the same tests

The server reports the [metrics](/docs/server/metrics) of each turn once its answer has been heard. `call.waitForMetrics(turn)` waits for them, and `expectLatency()` checks them against limits. With the fakes, the speech to text and the voice take no time, so the latency you measure is the one of your agent and its tools. With the real model, it catches a prompt that grew too long or a tool that turned slow:

```typescript
const turn = await call.say('Where is my order 42?')
expectLatency(await call.waitForMetrics(turn), { llm: 3000 })

const summary = await call.end()
expectLatency(summary.metrics, { llm: { median: 1500, p95: 3000 } })
```

A limit on a step that was not measured fails, so a limit never passes for want of a measure. In production, the same metrics feed [OpenTelemetry traces](/blog/opentelemetry-voice-agent-nodejs).

## Test turn taking with real audio

The text simulation skips the audio, which is where a voice agent fails in ways no transcript shows: a pause that cuts a sentence in two, a turn that closes late, an assistant that keeps talking over the user. `AudioTestCall` plays WAV files to your server in real time, 20 ms at a time, through your real speech to text, VAD and turn detector.

```bash
npm install @micdrop/openai @micdrop/silero @micdrop/smart-turn onnxruntime-node
```

`tests/audio.test.ts`

```typescript
import assert from 'node:assert/strict'
import { it } from 'node:test'
import { openai } from '@ai-sdk/openai'
import { OpenaiSTT } from '@micdrop/openai'
import { SmartTurn } from '@micdrop/smart-turn'
import {
  AudioTestCall,
  expectAnswer,
  readWav,
  TextTTS,
} from '@micdrop/testing'
import { createCallConfig } from '../src/agent'
import '@micdrop/silero/node'
import '@micdrop/smart-turn/node'

const createAudioConfig = () => ({
  ...createCallConfig(openai('gpt-5.2')),
  stt: new OpenaiSTT({ apiKey: process.env.OPENAI_API_KEY || '' }),
  // A silent voice, long enough to speak over
  tts: new TextTTS({ wordDuration: 200 }),
  turns: { vad: 'silero' as const, detector: new SmartTurn() },
})

it('hears a question spoken with a pause as one turn', async () => {
  const call = await AudioTestCall.start(createAudioConfig())
  await call.silence(500)
  const turn = await call.say(readWav('fixtures/order-with-pause.wav'))
  assert.equal(turn.userMessages.length, 1)
  expectAnswer(turn, 'shipped')
  await call.end()
})

it('stops talking soon after the user speaks over it', async () => {
  const call = await AudioTestCall.start(createAudioConfig())
  const question = call.say(readWav('fixtures/return-policy.wav'))
  await call.waitForAssistantSpeech()

  // The user speaks 300 ms into the answer
  const bargeIn = call.elapsed + 300
  await call.say(readWav('fixtures/stop.wav'), { at: bargeIn })

  assert.ok((await question).interrupted)
  const [speech] = call.assistantSpeech
  assert.ok(speech.end - bargeIn < 800, 'the voice stopped within 800 ms')
  console.log(call.formatTimeline())
  await call.end()
})
```

Record the fixtures once, with your own voice or a voice generated for the purpose, as 16 bit PCM WAV files: `readWav()` brings any rate to the 16 kHz the server hears. `formatTimeline()` prints what happened when: the audio played, the turns found, the messages, the tool calls and the moments the voice was dropped. The [interruption guide](/blog/voice-agent-interruption-barge-in) explains what a good barge in looks like.

These tests call your speech to text and your model on each run. Keep them for what only audio shows, and run them when the turn detection or the speech to text changes.

## Run them in CI

The offline tests run on every push. The tests that call providers run on demand and every night, with the key stored as a secret:

`.github/workflows/test.yml`

```yaml
name: Tests
on:
  push:
  workflow_dispatch:
  schedule:
    - cron: '0 3 * * *'

jobs:
  offline:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: npm test

  live:
    if: github.event_name != 'push'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: touch .env && npm run test:live
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
```

A nightly run catches what changes without a commit of yours: a provider that updates its model, or an API that slows down.

## What the library itself guarantees

Your tests cover your agent. What happens when a provider hangs, a tool throws or the user hangs up in the middle of an answer is covered by the [reliability scenarios](/docs/server/reliability) of Micdrop, written with the same kit and run on every change of the repository. They are public, so you can read exactly what the server does in each case before you write a test of your own for it.

## Hosted testing platforms

Coval, Cekura, Bluejay, Hamming and others run simulated callers as a service, with dashboards, personas, background noise and monitoring of live calls. The [ranking of voice agent testing tools](/blog/top-voice-agent-testing-tools) compares them. They test any agent from the outside, through a phone number or a WebSocket. `@micdrop/testing` works from the inside, in your test runner, with access to every tool call and handoff, at the cost of the model calls alone. The two fit together: unit and conversation tests in CI, a platform for scale and production monitoring.

## Frequently asked questions

### How do I unit test a voice agent?

Run the agent without its speech providers and drive it with text. In Micdrop, `TestCall` starts your real config with fakes for the speech to text and the voice, and `ScriptedAgent` replaces the model, so a test checks the tools, their parameters, the handoffs and the end of the call offline, in milliseconds.

### What is a simulated caller?

A program that plays the user of a voice agent: a persona with a goal, played by a language model or by a script. It talks to the agent until one of them hangs up, then assertions and a judge decide whether the conversation went well.

### Which test runner does @micdrop/testing need?

Any. The assertions throw a standard `AssertionError` from Node, so the same tests run in node:test, vitest or jest.

### Can I test interruptions and turn detection?

Yes, with `AudioTestCall`. It plays audio files in real time through your real speech to text, VAD and turn detector, places a sentence at a given moment of the call to speak over the assistant, and records when the voice stopped.

### Do the tests call paid APIs?

The text simulation with a scripted agent calls nothing. A simulated caller and a judge call the models you give them, and an audio simulation calls your speech to text and your model, so those runs cost what the providers charge for them.

## Getting started

The [testing documentation](/docs/server/testing) lists every option, assertion and record field, and the [testing example](https://github.com/Godefroy/micdrop/tree/main/examples/testing) runs the offline and live suites of this tutorial with `pnpm test` and `pnpm test:live`.

## Keep reading

[![Best Voice Agent Testing Tools in 2026](/_astro/thumbnail.plcudPJ5_2nAopq.webp)

November 8, 2026

## Best Voice Agent Testing Tools in 2026

Eight voice agent testing platforms ranked on what a web app agent needs: simulated callers without a phone number, regression tests in CI and call monitoring.



](/blog/top-voice-agent-testing-tools)

[

November 29, 2026

## Trace a Voice Agent in Node.js with OpenTelemetry

See where the silence of each turn goes, from the end of the user speech to the first word of the answer: one trace per call, a span per turn and per step, in Jaeger, Langfuse or any OTLP backend.



](/blog/opentelemetry-voice-agent-nodejs)

[![Voice Agent Barge-In: Handle Interruptions](/_astro/thumbnail.B5PI427Q_Z23btMG.webp)

October 31, 2026

## Voice Agent Barge-In: Handle Interruptions

A voice agent needs to detect speech during playback, stop every output path, cancel stale generation and keep only the answer the user heard.



](/blog/voice-agent-interruption-barge-in)
