Test with a fake backend
Test calls against a fake backend made from your endpoints.
Tests that call a real API are slow, flaky, and hard to point at an error
case. Effetch never touches the network itself: it sends every request
through the HttpClient you provide. In tests, @monarcode/effetch/test
gives you a fake one, made from your endpoints, so your code runs as it does
in production: the real client, with its plugins, defaultError and
statusErrors.
In this tutorial, you write a test file that answers three endpoints from a fake backend, then run it and check what comes back.
Before you begin
You need:
-
endpoints defined with
Fetch.endpoint(see Define endpoints); -
a test runner. This tutorial uses Vitest with
@effect/vitest, which runs an Effect as a test:npm install --save-dev vitest @effect/vitest
FetchTest doesn't depend on a test runner, so the same code works with Jest,
Bun or Deno: see Run it without Vitest.
Write the test
Create a file named todos.test.ts with the following content:
import { , } from "@effect/vitest";
import * as from "effect/Effect";
import * as from "effect/Layer";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch/test";
// 1. The endpoints, the client and the service your app already has
const = .({
: .,
: .,
: .,
});
const = .({ : ., : . });
class extends .<>()("TodoNotFound", {
: .,
}) {}
const = .("GET /todos/:id", {
: ,
: { 404: },
});
const = .("POST /todos", {
: ,
: ,
});
const = .("GET /todos", { : .() });
class extends .<>()("Api", {
: "https://api.test",
}) {}
class extends .<>()("TodoApi", , {
: ,
: ,
: ,
}) {}
// 2. A handler for each endpoint
const = .([
.(, ({ }) =>
// params are strings, as they are in the URL
.({
: (.),
: "Write docs",
: new (0),
}),
),
.(, ({ }) =>
.({ : 2, ... }),
),
.(, 503),
]);
// 3. The real client, sending its requests to the fake backend
const = ..(
.(.),
.(),
);
// 4. The tests, each one an Effect
.("gets a todo", () =>
.(function* () {
const = yield* ;
const = yield* .({ : { : 1 } });
(.).("Write docs");
// A Date again: it went over the wire as a string
(.).();
}).(.()),
);
.("fails when the list is unavailable", () =>
.(function* () {
const = yield* ;
const = yield* .(.());
().({ : "HttpError", : 503 });
}).(.()),
);Each numbered part of the file is one step:
- Define the endpoints. These are the same
Fetch.endpointdefinitions, client andFetch.Endpointsclass your app uses. In a real project, you import them rather than declare them in the test. - Write a handler for each endpoint.
FetchTest.respondanswers an endpoint with what its handler returns, andFetchTest.failanswers every request with an error status.FetchTest.layerturns the list into a fake backend. - Provide the fake backend.
FetchTest.layeris anHttpClientlayer (a layer is how Effect builds a service, such as the client, for a program that needs it), so it goes whereFetchHttpClient.layergoes in your app. Here it's provided underApi.layer, so the real client sends its requests to it. - Write the tests. Each test gets the service, makes a call, and
checks what comes back.
Effect.flipturns the failure into a value, so the second test can check the error.
Run the test
Run Vitest:
npx vitest runBoth tests pass:
Test Files 1 passed (1)
Tests 2 passed (2)The first test checks that todo.due is a Date. The handler returned a
Date, the fake backend encoded it as a string, and the client decoded it
back, as it would with a real server. The second checks that GET /todos
failed with an HttpError whose status is 503.
What a handler gets and returns
What a handler gets and returns is typed by its endpoint, and checked as a real backend would check it. The handler gets one object, with these properties:
paramshas the route's params, as strings.bodyis decoded with the endpoint'sinputschema, sobody.dueis aDatein the test. A multipart body is read back from the form, with its files asFiles.queryis decoded with the endpoint's query schema, if it has one. Otherwise, it's the raw query, as strings.headersare the request's headers, with lowercase names.urlis the URL the request was sent to.requestis the request itself, for anything else.
A handler returns an Effect that can't fail. What it succeeds with is sent back to the client:
- The result has
output's type, and is encoded withoutputbefore it's sent, so aDategoes over the wire as a string, as in production. WithFetch.text()orFetch.bytes(), it's sent as text or bytes. - Without
output, the result is sent by its runtime type, as a call'sbodywithoutinputis, andundefinedsends no body. - The status is 200, or 204 when there's no body to send.
To answer with another status or an error, return FetchTest.reply instead
(see Test errors and statuses).
A body, query or result that doesn't match its schema is a defect that names
the route: it's a bug in the code under test, or in the test. Handlers work
the same for definitions made with Fetch.endpoint, endpoints made with
api.endpoint or api.bind, and a Fetch.Endpoints class's
definitions.
Handlers that use services
A handler can use services, such as a clock or a store of fake data. The layer then needs those services to be built. Each handler runs with the services the layer was built with, plus those of the call it answers. When both have the same service, the call's wins.
Slow responses
A handler is an Effect, so it can wait before it answers, which lets you
test a timeout plugin or a loading state:
import * as from "effect/Effect";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch/test";
const = .({ : ., : . });
const = .("GET /todos/:id", { : });
// Answers after 2 seconds
export const = .([
.(, () =>
.(.("2 seconds"), { : 1, : "Write docs" }),
),
]);it.effect runs a test on a test clock, which only moves when you move it,
so a handler that sleeps waits forever. Run the test with it.live instead,
or fork the call and move the clock with TestClock.adjust.
What the fake backend can't do is send a body in pieces: it sends the whole body at once. For a body that arrives slowly or breaks off, see Use a hand-written HttpClient.
Run it without Vitest
A test is an Effect, so any runner can run it with Effect.runPromise. With
Jest, Bun or Deno, write the test as an Effect that uses your runner's
expect, as in Write the test, and run it inside the
runner's test function:
import * as from "effect/Effect";
// The Effect of a test, with Effect.provide(TestLayer) applied
declare const : .<void>;
// Inside your runner's test function:
await .();A failed expect throws inside the Effect, so runPromise rejects and the
test fails. A call that fails with an error you didn't catch rejects it too.
What's next
- Test errors and statuses: make the fake backend fail, or answer with another status.
- Check what was sent: assert on the requests your code sent, and see how routes match them.
- Test stream endpoints: answer a stream endpoint with a list of events or values.
- Use a hand-written HttpClient: fake a network failure, or a body that arrives slowly or breaks off.