Skip to Content
Testing

Test stream endpoints

Fake a streamed response with a list of events or values.

Code that reads Server-Sent Events or newline-delimited JSON is easiest to test when you control exactly what the server sends. The fake backend answers a stream endpoint from a list, so you can test how your code handles each event or value. This page shows how.

Answer with a list

A handler for a stream endpoint returns a list, and FetchTest sends it as the stream's body. The following backend sends two events for a job:

import * as  from "effect/Effect";
import * as  from "effect/Schema";

import {  } from "@monarcode/effetch";
import {  } from "@monarcode/effetch/test";

const  = .({ : . });

const  = .("GET /jobs/:id/events", {
  : ,
  : "sse",
});

export const  = .([
  .(, ({  }) =>
    .([
      { : { : 50 } },
      { : "done", : ., : { : 100 } },
    ]),
  ),
]);

What the list holds depends on the endpoint's stream:

  • For stream: "sse", the list holds events, each with its data and an optional event and id.
  • For stream: "ndjson", the list holds values.

Each value is encoded with the endpoint's output before it's sent, as a plain response is.

Test slow or broken streams

The fake backend sends the whole body at once. To test how your code handles values that arrive slowly, or a body that breaks off partway, use a hand-written HttpClient whose response has a ReadableStream body.

What's next

On this page