Open History to see the last commit
1---
2title: Test with a Fake Model
3id: testing
4order: 12
5description: "Test chat(), tools, and middleware with no network and no API key. fakeText() from @tanstack/ai/testing answers from a script and estimates token usage."
6keywords:
7 - tanstack ai
8 - testing
9 - fake adapter
10 - mock model
11 - unit tests
12 - fakeText
13---
14
15The test adapter returns a scripted stream. Tests then skip the network, the API key, and a different answer on each run.
16
17Use `fakeText()` from `@tanstack/ai/testing`. It is a text adapter that answers from a script that you write. Give it to `chat()` like any other adapter.
18
19## Quick setup
20
21Queue the answers, then run `chat()`:
22
23```ts
24import { chat } from '@tanstack/ai'
25import { fakeText } from '@tanstack/ai/testing'
26
27const fake = fakeText()
28fake.setResponses([{ text: 'Hello!' }])
29
30let answer = ''
31for await (const chunk of chat({
32 adapter: fake,
33 messages: [{ role: 'user', content: 'Hi' }],
34 threadId: 'thread-1',
35})) {
36 if (chunk.type === 'TEXT_MESSAGE_CONTENT') answer += chunk.delta
37}
38console.log(answer) // 'Hello!'
39```
40
41Run it. It prints `Hello!` with no network and no key.
42
43## How it works
44
45- Each model call takes the next answer from the queue.
46- An empty queue ends the call with a `RUN_ERROR`: "No more fake responses queued".
47- `appendResponses` adds answers. `pendingResponses()` counts the answers that are left.
48- `fake.state.callCount` counts the model calls that the fake answered.
49- The fake reports token usage on each call: `ceil(characters / 4)` over the request and the answer. So a long message costs many tokens, as with a real model.
50
51## Test a tool
52
53Give an answer with `toolCalls`, and `chat()` runs your tool. Then queue the answer that comes after the tool result:
54
55```ts
56import { chat, toolDefinition } from '@tanstack/ai'
57import { fakeText } from '@tanstack/ai/testing'
58import { z } from 'zod'
59
60const getWeather = toolDefinition({
61 name: 'get_weather',
62 description: 'Get the weather in a city',
63 inputSchema: z.object({ city: z.string() }),
64}).server(async ({ city }) => ({ city, sky: 'sunny' }))
65
66const fake = fakeText()
67fake.setResponses([
68 { toolCalls: [{ name: 'get_weather', input: { city: 'Oslo' } }] },
69 { text: 'It is sunny in Oslo.' },
70])
71
72for await (const chunk of chat({
73 adapter: fake,
74 messages: [{ role: 'user', content: 'Weather in Oslo?' }],
75 threadId: 'thread-1',
76 tools: [getWeather],
77})) {
78 if (chunk.type === 'TOOL_CALL_RESULT') console.log(chunk.content)
79}
80console.log(fake.state.callCount) // 2
81```
82
83## Test an error
84
85Give an answer with `error`, and the call fails with a `RUN_ERROR`:
86
87```ts
88import { chat } from '@tanstack/ai'
89import { fakeText } from '@tanstack/ai/testing'
90
91const fake = fakeText()
92fake.setResponses([{ error: 'The provider is down' }])
93
94for await (const chunk of chat({
95 adapter: fake,
96 messages: [{ role: 'user', content: 'Hi' }],
97 threadId: 'thread-1',
98})) {
99 if (chunk.type === 'RUN_ERROR') console.log(chunk.message) // 'The provider is down'
100}
101```
102
103## Advanced
104
105### Answer from the request
106
107Put a function in the queue to build the answer when the call comes in. It gets the `request` and the `state`:
108
109```ts
110import { fakeText } from '@tanstack/ai/testing'
111
112const fake = fakeText()
113fake.setResponses([
114 ({ request, state }) => ({
115 text: `Call ${state.callCount} saw ${request.messages.length} messages.`,
116 }),
117])
118```
119
120### Options
121
122| Option | What it does |
123|---|---|
124| `model` | The model id. Default `'fake-model'`. |
125| `input` | The input kinds that the model reads, for example `['text', 'image']`. Read it back as `fake.inputModalities`, to test code that checks what a model accepts. |
126| `contextWindow` | The context window in tokens. Read it back as `fake.contextWindow`. |
127| `tokensPerSecond` | Stream the text at this speed, 4 characters for each token. |
128| `cache` | With a `threadId`, the part of the request that matches the previous request of the thread counts as cached tokens. |
129
130### Answer fields
131
132| Field | What it does |
133|---|---|
134| `text` | The visible answer. |
135| `thinking` | Thinking text, streamed before the answer. |
136| `toolCalls` | `{ name, input?, id? }` calls for `chat()` to run. |
137| `finishReason` | `'stop'`, `'length'`, `'content_filter'`, or `'tool_calls'`. Default `'tool_calls'` with tool calls, else `'stop'`. |
138| `error` | Fail the call with a `RUN_ERROR` that has this message. |
139
140Your tests now run with no network and no key, and they get the same answer each time.