Test errors and statuses
Make the fake backend fail or answer with another status.
This page shows how to make the fake backend answer with an error, or with another status, so you can test how your code handles each one.
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. The body is encoded with the endpoint's
statusErrors schema for that status, then its error schema, so the client
decodes it back into your domain error:
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch/test";
class extends .<>()("TodoNotFound", {
: .,
}) {}
const = .("GET /todos/:id", {
: { 404: },
});
export const = .([
// The call fails with a TodoNotFound.
.(, 404, new ({ : "No todo 9" })),
]);Answer with another status
A handler answers with another status by returning
FetchTest.reply(status, body), such as a 404 for one id and the todo for
the others. A reply's body is sent as it is, as a call's body without
input is:
- no body
- a string as text
- bytes as bytes
- a
Blob,FormDataorURLSearchParamsas it is - anything else as JSON
For a 2xx with a typed body, such as a 201, pass { status: 201 } as
respond's third argument instead.
The following backend answers 404 for every todo but the first, and 201
with a location header when a todo is created:
import * as from "effect/Effect";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch/test";
const = .({ : ., : . });
const = .("GET /todos/:id", { : });
const = .("POST /todos", {
: .({ : . }),
: ,
});
export const = .([
.(, ({ }) =>
.(
. === "1"
? { : 1, : "Write docs" }
: .(404, { : `No todo ${.}` }),
),
),
.(
,
({ }) => .({ : 2, ... }),
{
: 201,
: { : "/todos/2" },
},
),
]);What's next
- Errors by status: declare the domain errors
that
FetchTest.failencodes. - Check what was sent: assert on the requests your code sent.
- Use a hand-written HttpClient: fake a network failure, which the fake backend doesn't do.