javascript / expert
Snippet
Mocking ReadableStream Async Generators for Next.js Server Component Testing
In Next.js App Router unit testing, Server Components and API routes streaming responses require mocking ReadableStream objects. By defining a custom pull controller method, developers simulate incremental chunk delivery in server environments.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
export function createStreamMock(chunks: string[]): ReadableStream<Uint8Array> {const encoder = new TextEncoder();return new ReadableStream({async pull(controller) {if (chunks.length === 0) {controller.close();return;}controller.enqueue(encoder.encode(chunks.shift()));}});}
nextjs
Breakdown
1
export function createStreamMock(chunks: string[]): ReadableStream<Uint8Array> {
Defines a helper function returning a typed ReadableStream of Uint8Array binary chunks.
2
const encoder = new TextEncoder();
Instantiates TextEncoder to translate UTF-8 string chunks into binary byte arrays.
3
return new ReadableStream({
Creates a Web Streams API ReadableStream instance used in Next.js response streaming.
4
async pull(controller) {
Implements the underlying source pull strategy invoked whenever the stream reader requests data.
5
if (chunks.length === 0) {
Checks if all queued text chunks have been processed from the mock stream data payload.
6
controller.close();
Signals stream termination to the consumer when no chunks remain.
7
return;
Exits the pull loop execution early.
8
}
Closes conditional branch.
9
controller.enqueue(encoder.encode(chunks.shift()));
Removes the head element, encodes it into Uint8Array bytes, and enqueues it to stream consumers.
10
}
Closes pull method implementation.
11
});
Ends stream configuration object passed to ReadableStream constructor.
12
}
Closes function body.