# Test stream endpoints (https://effetch.monarcode.dev/docs/testing/streams)

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](https://effetch.monarcode.dev/docs/testing) answers a [stream endpoint](https://effetch.monarcode.dev/docs/streaming)
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:

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

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

const JobEvent = Schema.Struct({ percent: Schema.Finite });

const jobEvents = Fetch.endpoint("GET /jobs/:id/events", {
  output: JobEvent,
  stream: "sse",
});

export const Backend = FetchTest.layer([
  FetchTest.respond(jobEvents, ({ params }) =>
    Effect.succeed([
      { data: { percent: 50 } },
      { event: "done", id: params.id, data: { percent: 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`](https://effetch.monarcode.dev/docs/testing/http-client#send-a-body-that-breaks-off)
whose response has a `ReadableStream` body.

## What's next

- [Streaming responses](https://effetch.monarcode.dev/docs/streaming): see how stream endpoints read
  events and values, and how a stream fails.
- [Use a hand-written HttpClient](https://effetch.monarcode.dev/docs/testing/http-client): send a body
  that arrives slowly or breaks off.
- [Check what was sent](https://effetch.monarcode.dev/docs/testing/requests): assert on the requests your
  code sent.