Check what was sent
Assert on the requests your code sent, and learn how they're matched.
This page shows how to read the requests the fake backend received, so you can assert on what your code sent, and explains how the fake backend matches each request to a handler.
Read the recorded requests
The layer also provides FetchTest.Recorder, which keeps every request it
received, with a new record each time the layer is built.
FetchTest.requests reads it. Under a client's layer, Layer.provide would
hide it, so use Layer.provideMerge:
import * as from "effect/Effect";
import * as from "effect/Layer";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch/test";
class extends .<>()("Api", {
: "https://api.test",
}) {}
const = .("DELETE /todos/:id");
const = .([
.(, () => .),
]);
export const = .(function* () {
const = yield* ;
yield* .()({ : { : 1 } });
const [] = yield* .;
// sent.method: "DELETE", sent.url: "https://api.test/todos/1",
// sent.route: "DELETE /todos/:id", sent.params: { id: "1" }
return ;
}).(.(..(.())));Each recorded request has its method, url, the route and params it
matched, its raw query, its headers, and its body, read back as JSON,
text or bytes.
How requests are matched
The fake backend picks a handler for each request by these rules:
-
Method and path. A route matches a request with the same method, whose path ends with the route's path. So
GET /todos/:idanswershttps://api.test/v1/todos/1, whatever the client'sbaseUrl. To match the whole URL instead, pass thebaseUrlto the layer:FetchTest.layer(handlers, { baseUrl: "https://api.test/v1" }). -
The root route,
GET /, matches the path/alone, since every path with a trailing slash ends with it. Under abaseUrlwith a path, pass thatbaseUrlto the layer. -
The best match wins. When several routes match, the one with the most segments wins, then the one with the most literal segments, so
GET /todos/countwins overGET /todos/:id. After that, the one listed first wins. -
Absolute routes such as
POST https://uploads.example.com/filesmatch that URL only. -
No match is a defect, whose message lists the backend's routes, and the ones that match the path with another method:
FetchTest: no handler for POST https://api.test/todos/1. GET /todos/:id matches its path, but not its method. The handlers are: - GET /todos/:id
What's next
- Test errors and statuses: make the fake backend fail, or answer with another status.
- Use a hand-written HttpClient: fake what the fake backend doesn't do, such as a network failure.
- FetchTest: every member of the
FetchTestnamespace.