A streamed-response test becomes flaky when it waits for a fixed number of chunks or sleeps for a few seconds until the text looks complete. The result depends on CI scheduling, transport buffering, and how the provider split the data, rather than the behavior you meant to verify.
Separate two boundaries. First, turn SDK or transport output into events owned by your application. Then test that state machine with a local sequence of start, delta, done, error, and cancel. The guide to testing an AI agent without extra LLM calls uses the same provider-free boundary while keeping the important runner code under test.
This article tests the stream, not a live model request. For delivering progress to a UI, see how to stream AI agent progress to a UI. The screen and the test can share an event contract, but they have different oracles.
Short answer
- Normalize provider chunks into events owned by your application.
- Check start, partial text, terminal state, and error, not the duration of each token.
- Use a local async fixture and
node:test; do not usesleepto synchronize the test.- Assert exact event order only when the transport contract is the subject of the test.
What should a streaming test prove?
Start with the state the consumer needs to know. A small contract can look like this:
| Event | Useful transition | Stable assertion |
|---|---|---|
start |
waiting to streaming |
The consumer opens a response and does not mark it complete. |
delta |
appends text or data | The fragment is added without removing the received prefix. |
done |
streaming to complete |
The response ends once and exposes accumulated text. |
error |
streaming to error |
The error is observable and partial text is not treated as complete. |
cancel |
streaming to cancelled |
The consumer stops reading and does not wait for a done that will not come. |
These names are a domain proposal, not a promise about an SDK. The transport may provide SSE, ReadableStream objects, or agent-specific events. The adapter should translate those forms into a contract that the UI and tests can understand.
Separate the application contract from the provider stream
The Agents SDK testing guide separates ordinary response tests from exact stream-event tests. It recommends the latter when ordering, partial output, cancellation, or malformed streams are the behavior under investigation. For most workflows, a normalized result is a smaller and more stable surface.
This keeps the test from knowing details that do not belong to the domain. A provider may split a word into two deltas today and send it in one delta tomorrow. If your application contract is final text and terminal states, that change should not break the consumer suite.
An adapter can perform the conversion:
function toAppEvent(providerEvent) {
if (providerEvent.kind === "message-start") return { type: "start" };
if (providerEvent.kind === "text-delta") {
return { type: "delta", text: providerEvent.text };
}
if (providerEvent.kind === "message-stop") return { type: "done" };
return { type: "error", message: "unrecognized provider event" };
}
This is illustrative. A real adapter must handle every documented provider event, including parsing failures and cancellation. Test the translation of each provider shape at the adapter boundary. Let the consumer test use only application events.
Build a deterministic fixture with node:test
A local fixture does not need a connection to test text accumulation and state transitions. An async generator reproduces the reading boundary while keeping the sequence fully controlled:
import assert from "node:assert/strict";
import test from "node:test";
async function* scripted(events) {
for (const event of events) yield event;
}
async function consumeAssistantStream(source, snapshots) {
let state = { status: "waiting", text: "", error: null };
snapshots.push({ ...state });
for await (const event of source) {
if (event.type === "start") {
state = { ...state, status: "streaming" };
} else if (event.type === "delta") {
state = { ...state, text: state.text + event.text };
} else if (event.type === "done") {
state = { ...state, status: "complete" };
} else if (event.type === "error") {
state = { ...state, status: "error", error: event.message };
}
snapshots.push({ ...state });
if (state.status === "complete" || state.status === "error") break;
}
if (state.status === "streaming") {
throw new Error("stream ended without a terminal event");
}
return state;
}
test("accumulates deltas and completes without measuring time", async () => {
const snapshots = [];
const result = await consumeAssistantStream(
scripted([
{ type: "start" },
{ type: "delta", text: "partial " },
{ type: "delta", text: "answer" },
{ type: "done" },
]),
snapshots,
);
assert.equal(result.status, "complete");
assert.equal(result.text, "partial answer");
assert.ok(snapshots.some((snapshot) => snapshot.text === "partial "));
});
test("preserves partial text when the stream fails", async () => {
const result = await consumeAssistantStream(
scripted([
{ type: "start" },
{ type: "delta", text: "visible part" },
{ type: "error", message: "connection closed" },
]),
[],
);
assert.equal(result.status, "error");
assert.equal(result.text, "visible part");
assert.equal(result.error, "connection closed");
});
Save the example as stream-consumer.test.js and run node --test stream-consumer.test.js. The Node.js test runner API provides the runner and assertions used here. The fixture calls no LLM, uses no network, and does not wait on the real clock. Its local result proves only the transitions in the consumer you wrote.
Prefer invariants to chunk counts
Useful assertions describe what the system must preserve:
- a
deltaappends data without replacing the prefix already received; doneproduces exactly one complete state;erroris not converted into a complete response merely because partial text exists;- a stream ending in
streamingis an explicit failure, not a silent success; - cancellation stops reading and releases the resource according to the adapter;
- public state does not accidentally expose provider-internal events.
Avoid asserting that three chunks always arrive, that every chunk contains one word, or that every token appears within 100 milliseconds. Those properties can matter in a transport contract test, but they are poor oracles for an application consumer.
There is a legitimate exception. If your product depends on event order, specific partial output, cancellation, or rejection of malformed messages, write a separate test for that boundary. The Agents SDK documentation makes the distinction between response tests and exact stream tests explicit. The point is to make clear which detail is frozen.
When to test real SSE
A local fixture does not prove that an HTTP endpoint frames events correctly. When that is the question, add a small controlled integration test. The server should expose the expected Content-Type and send each event in the documented format. In the SSE convention described by MDN, event fields are separated by line breaks and a block ends with a blank line.
Do not assume [DONE] is universal, that every data field is JSON, or that every event equals one token. Those are endpoint or SDK details. Test the format you chose to document, then translate it into application events.
On the consumer side, a ReadableStream can be consumed asynchronously. The Node.js Web Streams API documents that iteration and iterator shutdown behavior. The test should still finish through a terminal event or controlled cancellation, not through a setTimeout hoping the response arrives.
What this fixture does not prove
The local test is deliberately small. It does not prove:
- that a provider sends the same events in a real response;
- that a proxy will not group or delay bytes;
- that a browser updates the screen at the same pace as the server;
- that authentication, usage limits, and endpoint retries work;
- that a model will choose the same response in another run.
Choose a matching proof for each limit: adapter test, HTTP integration, browser test, operational contract, or behavior evaluation. Do not turn a deterministic test into evidence about the model or network.
CI checklist
- Define public states and the events that change them.
- Put the provider adapter behind an application interface.
- Write a fixture with at least one complete case, one partial delta followed by an error, and one cancellation case.
- Check accumulated text, terminal state, and resource cleanup.
- Add an integration test for the HTTP or SSE framing you actually publish.
- Run
node --testwithout sleeps or external calls in the fast suite. - Keep real-provider tests in a separate layer with explicit cost, credentials, and variability.
If the failure is a deadline, keep the questions separate. The AI agent tool-timeout test without duplicate effects shows how to control a deadline and inspect external state. That case tests a time policy; this one tests the evolution of partial response state.
Method and limits
The author is Samuel Fajreldines. The original proof is the local fixture above, executed with Node.js 25.5.0 without a provider, network, or benchmark. The technical research used the linked documentation, while live search results were used only to understand language and apparent gaps.
AI tools may help organize sources and revise prose, but they do not replace running the test. For this article, RemoteCode is the author's tool for working with code and agents; the link is not a performance claim or independent validation.
The next boundary is deciding which invariants belong to your product. The guide to regression testing agents without exact text comparison helps when the question becomes behavior rather than transport. For agent action order, use AI agent trajectory testing.
Sources consulted
- OpenAI Agents SDK, Testing, retrieved November 24, 2026.
- Node.js, Web Streams API, retrieved November 24, 2026.
- Node.js, Test runner, retrieved November 24, 2026.
- MDN, Using server-sent events, retrieved November 24, 2026.