Streaming tests
Provide predictable delayed output while testing code that consumes streams.
AI Tools · Function
Creates a ReadableStream that emits supplied values in order with optional initial and inter-chunk delays. It is mainly useful for testing streaming behavior or reproducing time-delayed responses.
The utility builds a generic ReadableStream from an ordered chunks array. It can pause before the first emission and between later emissions, or skip either delay with null, then closes after the final chunk.
simulateReadableStream<T>({ chunks, initialDelayInMs?, chunkDelayInMs? }): ReadableStream<T>| Name | Type | Description |
|---|---|---|
chunks | T[] | Array of values to emit sequentially. |
initialDelayInMs | number | null | Optional milliseconds to wait before the first value; defaults to 0, or null to skip the initial delay. |
chunkDelayInMs | number | null | Optional milliseconds to wait between values; defaults to 0, or null to skip inter-chunk delays. |
ReadableStream<T> that emits the provided chunks in sequence and closes after the last one.
import { simulateReadableStream } from 'ai';
const stream = simulateReadableStream({
chunks: ['Hello', ' ', 'world!'],
initialDelayInMs: 100,
chunkDelayInMs: 50,
});
for await (const chunk of stream) {
process.stdout.write(chunk);
}Creates a stream that emits three strings after an initial pause and then at fixed intervals.
Provide predictable delayed output while testing code that consumes streams.
Recreate progressive model-like output from saved chunks.
Exercise UI or transport behavior under controlled latency.
It accepts an array of values and returns a ReadableStream that emits them in order. The stream closes automatically once every value has been emitted.
Follow-up: How would you model a stream of structured events?
initialDelayInMs controls the wait before the first value, while chunkDelayInMs controls the wait between later values. Both default to zero when omitted.
Follow-up: How can you create a stream with no artificial timing?
Set either delay option to null to omit that delay entirely. This is useful when tests need deterministic immediate delivery rather than simulated latency.
Follow-up: How could you test a consumer's handling of progressive output?
ReadableStreamstreamTextMockLanguageModelV4