Testing
Test queries, mutations and components with a fake backend and a fresh client.
You want tests for your queries, mutations and components that run fast
and don't touch the network. Your queries run against whatever
HttpClient your client's layer gets, so a test gives it a fake backend,
and a fresh client for each test, so no test sees another's cache. This
page uses Vitest; the same setup works with any test
runner.
The examples import api.ts, todos.ts, toggle-todo.ts and
open-todos.tsx from Getting started.
Fake the backend
Effetch's FetchTest.layer, from @monarcode/effetch/test, is a fake
backend made from your endpoints. Each handler answers one endpoint, with
its params, body and response typed by the endpoint. Provide it to your
client's layer in place of FetchHttpClient.layer:
import * as from "effect/Effect";
import * as from "effect/Layer";
import * as from "effect/Schema";
import { } from "@monarcode/effetch";
import { } from "@monarcode/effetch/test";
import { , } from "./api.js";
import { , } from "./todos.js";
// The route toggleTodo calls, for its handler.
const = .("PATCH /todos/:id", {
: .({ : . }),
: ,
});
const = .([
.(, () =>
.([{ : 1, : "Write tests", : false }]),
),
.(, ({ }) =>
// params are strings, as they are in the URL
.({
: (.),
: "Write tests",
: false,
}),
),
.(, ({ , }) =>
.({ : (.), : "Write tests", ... }),
),
]);
export const = ..(.());Provide the fake to ApiClient.layer, as ApiClientTest does, not around
the client. A class that overrides layer to provide its own HttpClient
ignores one given from outside. Effetch's
docs cover FetchTest in full, including
recording the requests a test sent.
Test a query
QueryClient.layer gives an Effect program a client, disposed when the
program ends. Give it Signals.none, which never reports a focus or a
reconnect, so nothing in a test refetches on its own:
import * as from "effect/Effect";
import * as from "effect/Layer";
import { } from "@monarcode/effetch/test";
import { , , } from "@monarcode/effetch-query";
import { , } from "vitest";
import { } from "./api.js";
import { } from "./backend.js";
import { , , } from "./todos.js";
const = .({
: ,
: .,
});
("loads a todo", async () => {
const = await .(
.(({ : { : 1 } })).(.()),
);
().({ : 1, : "Write tests", : false });
});
("fails when the server is down", async () => {
const = ..(
.(.([.(, 503)])),
);
const = await .(
.(.(())).(
.(.({ : , : . })),
),
);
(.).("HttpError");
});The second test gives the client a backend that answers GET /todos with
a 503. Effect.flip turns the query's typed error into the value, so the
test can check it.
Test a mutation
Mutation.run runs a mutation from Effect, with your services and the
client. queryClient.runPromise provides both:
import { , , } from "@monarcode/effetch-query";
import { , } from "vitest";
import { } from "./backend.js";
import { } from "./toggle-todo.js";
("saves a toggle", async () => {
const = .({
: ,
: .,
});
const = await .(
.(, { : { : 1 }, : { : true } }),
);
().({ : 1, : "Write tests", : true });
await .();
});A run goes through every step a component's run does: its optimistic
writes, its invalidates and its callbacks. So a test can run a mutation,
then read the queries it changed with Query.get or Query.fetch.
Test a component
Render the component under a QueryProvider with a fresh client, and
dispose the client after each test. The test needs a DOM, such as
Vitest's happy-dom or jsdom environment, and React Testing Library:
// @vitest-environment happy-dom
import { , , } from "@testing-library/react";
import { , , , } from "vitest";
import { , } from "@monarcode/effetch-query";
import { } from "@monarcode/effetch-query/react";
import { } from "./backend.js";
import { } from "./open-todos.js";
let : .;
(() => {
= .({
: ,
: .,
});
});
(async () => {
();
await .();
});
("lists the open todos", async () => {
(
< ={}>
< />
</>,
);
(.("Loading…")).();
(await .("Write tests")).();
});findByText waits for the fetch to settle and the list to render.
Disposing the client in afterEach stops what it still runs, so
nothing from one test reaches the next.
Control time
To test staleTime, refetchInterval or gcTime, fake only the timers
and Date, then move them with vi.advanceTimersByTimeAsync. Leave
setImmediate real: Effect's scheduler runs on it, so faking it stalls
every Effect until the timers move. Effect's own TestClock doesn't reach
the cache, whose timers run with the client's layer rather than the test's
services.
This test counts the requests the backend answers, and checks that todo,
whose staleTime is 1 minute, refetches only after a minute:
import * as from "effect/Effect";
import * as from "effect/Layer";
import { } from "@monarcode/effetch/test";
import { , } from "@monarcode/effetch-query";
import { , , , } from "vitest";
import { } from "./api.js";
import { , } from "./todos.js";
(() => {
.();
});
("refetches a todo after its staleTime", async () => {
.({ : ["setTimeout", "clearTimeout", "Date"] });
let = 0;
const = ..(
.(
.([
.(, ({ }) =>
.(() => {
++;
return { : (.), : "Write tests", : false };
}),
),
]),
),
);
const = .({
: ,
: .,
});
const = () => .(({ : { : 1 } }));
await ();
await ();
().(1);
await .(60_000);
await ();
().(2);
await .();
});The second load() returns the cached value, since it's still fresh. A
minute later, the value is stale, so the third fetches again.
What's next
- Examples: complete apps, with the tests that drive them in a browser environment.
- The query client: the options a test client takes, and
what
dispose()releases. - Focus and online signals: what
Signals.nonereplaces.