# Test errors and statuses (https://effetch.monarcode.dev/docs/testing/errors)

The error paths of your code are the hardest to reach against a real API:
you can't ask a server for a 503 on demand. With the
[fake backend](https://effetch.monarcode.dev/docs/testing), you can answer any request with an error, or
with a status other than 200, and check that your code handles each one.
This page shows both.

## Fail every request to an endpoint

To answer every request to an endpoint with an error, use `FetchTest.fail`,
with a status and an optional body:

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

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

class TodoNotFound extends Schema.TaggedError<TodoNotFound>()("TodoNotFound", {
  message: Schema.String,
}) {}

const getTodo = Fetch.endpoint("GET /todos/:id", {
  statusErrors: { 404: TodoNotFound },
});
const listTodos = Fetch.endpoint("GET /todos");

export const Backend = FetchTest.layer([
  // The call fails with a TodoNotFound.
  FetchTest.fail(getTodo, 404, new TodoNotFound({ message: "No todo 9" })),
  // The call fails with an HttpError, status 503, asking to retry in 1 second.
  FetchTest.fail(listTodos, 503, undefined, {
    headers: { "retry-after": "1" },
  }),
]);
```

`FetchTest.fail` encodes the body as JSON with the first schema that
encodes it: the endpoint's `statusErrors` schemas for that status, then its
`error` schema. The client then decodes it back into your domain error, or
into `HttpError.body`. Without a body, the response is empty, so the call
fails with an `HttpError`.

A few more rules apply:

- **The status** must be from 300 to 599, since `fail` answers with an
  error.
- **Headers** go in the fourth argument, such as `retry-after` to test the
  `retry` plugin.
- **The client's maps.** A `Fetch.endpoint` definition doesn't carry the
  client's `statusErrors` or `defaultError`. Without schemas of its own, the
  body is sent by its runtime type, so an error class goes as JSON. The
  client still decodes it with its own maps, so
  `FetchTest.fail(getTodo, 401, new SessionExpired(…))` fails with
  `SessionExpired` when only the client maps 401. You don't need to repeat
  the map on the endpoint.
- **A body that no schema encodes** is a defect, since it's a bug in the
  test.

## Answer with another status

To fail some requests and answer others, return `FetchTest.reply(status,
body)` from a `respond` handler. The following backend answers `404` for
every todo but the first, and `201` with a `location` header when a todo is
created:

```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 Todo = Schema.Struct({ id: Schema.Finite, title: Schema.String });
const getTodo = Fetch.endpoint("GET /todos/:id", { output: Todo });
const createTodo = Fetch.endpoint("POST /todos", {
  input: Schema.Struct({ title: Schema.String }),
  output: Todo,
});

export const Backend = FetchTest.layer([
  FetchTest.respond(getTodo, ({ params }) =>
    Effect.succeed(
      params.id === "1"
        ? { id: 1, title: "Write docs" }
        : FetchTest.reply(404, { message: `No todo ${params.id}` }),
    ),
  ),
  FetchTest.respond(
    createTodo,
    ({ body }) => Effect.succeed({ id: 2, ...body }),
    {
      status: 201,
      headers: { location: "/todos/2" },
    },
  ),
]);
```

A reply's body isn't checked against the endpoint's schemas. It's sent as
it is, the way a call's `body` without `input` is:

- `undefined` as no body;
- a string as text;
- bytes as bytes;
- a `Blob`, `FormData` or `URLSearchParams` as it is;
- anything else as JSON.

For a 2xx with a typed body, such as a `201`, don't use `reply`. Pass
`{ status: 201 }` as `respond`'s third argument instead, as `createTodo`
does, so the body is still encoded with `output`.

## What's next

- [Errors by status](https://effetch.monarcode.dev/docs/errors/status-errors): declare the domain errors
  that `FetchTest.fail` encodes.
- [Check what was sent](https://effetch.monarcode.dev/docs/testing/requests): assert on the requests your
  code sent.
- [Use a hand-written HttpClient](https://effetch.monarcode.dev/docs/testing/http-client): fake a network
  failure, which the fake backend doesn't do.