You need: a scaffolded project. The wiring is already there.
A test that mocks D1 proves the mock works
Live fixtures is the case where the real account is the point, migrations is what a workers test runs first, and CI/CD is where all of it is enforced.
That is the kit’s whole testing argument, and it is why the scaffold ships two test configurations rather than one.
Workers tests run inside the real runtime, against real D1 and real KV through the local emulator. Everything else runs in Node.
The split is by filename, so a test lands in the right runtime by being named for it.
What is scaffolded
pithy init writes both configurations, the bindings the Workers half needs, and a matching ambient type declaration — plus a passing binding test, so the fiddly half is proven before you write anything.
A binding lives in two places: the test configuration and the type declaration. pithy add writes a capability’s test bindings into both, and pithy remove takes them out of both, so adding secrets leaves the first Workers test passing. A binding your own code needs goes in both by hand. That is the one thing to remember.
A Durable Object, a Workflow or a remote binding such as Vectorize is the exception: the project-wide test configuration cannot provide one on its own, so pithy add names it in its notes instead, and a Workers test that sends a request through that Worker’s fetch answers 500 without it. pithy doctor names any composed capability whose test bindings are missing.
A package the Workers config imports belongs in the root package.json. vitest.workers.config.ts loads from the project root, and under a package manager that does not hoist, such as Bun’s isolated linker or pnpm, the root resolves only what it declares itself. A package only a Worker declares fails the Workers tests with ERR_MODULE_NOT_FOUND after a clean install. pithy add declares the package a test binding imports as a root devDependency, such as @pithy-sh/secrets for the test master key, and pithy doctor names one the root cannot resolve. An import you add to the config yourself goes in the root package.json by hand.
What to test in which runtime
In the Workers runtime: anything touching a database, a namespace, a Durable Object or a binding. Repository functions, migrations, route handlers with real storage behind them.
In Node: pure logic. Codecs. Schema validation. Anything with no platform in it.
When in doubt, the Workers runtime is the safer answer — it is slower and it is correct.
Testing a route
Call the handler with a real request against a real database. No mock, no fixture layer, no in-memory substitute:
const res = await app.request("/notes", { headers: { authorization: `Bearer ${token}` } });
expect(res.status).toBe(200);The tables are there because the migrations ran. The migrations are the same ones production runs.
Test the rollback
Every migration’s down is tested, and that is the kit’s own standard rather than a suggestion.
The reason is that a rollback is the one piece of code you need under pressure and have never run. On dev, pithy migrate --rollback --group <group> reverses the run that applied it and asks for no confirmation phrase, which is what makes exercising it cheap.
Every codec round-trips in tests for the same reason: a conversion that is wrong in one direction is a data loss that shows up months later.
Where a Workflow is hard, and what to do
A durable job is genuinely awkward to test end to end, because the interesting behavior is in the retries and the checkpointing.
Test the step, not the Workflow. A step is a function; hand it what the runtime would and assert what it returns. The orchestration is the platform’s, and testing the platform is not your job.
Then prove the wiring once — that the binding exists and the job dispatches — rather than re-proving the runtime on every job.
Drive the real engine when the overlap is the point. Two runs that interleave — a cron run over a manual one, a retry over the original — is behavior no single step shows. A Workers test can run the real Workflows engine the local emulator ships, but you wire a Workflow of your own by hand, in three places:
- A
mainmodule that exports the Workflow class. The scaffoldedvitest.workers.config.tssets nomain, so add one tocloudflareTest({ main }), such asmain: "./apps/<worker>/src/test-main.ts", and export the class from that module. - A
workflowsentry in the same config’sminiflareblock, naming the binding, the Workflow and the class:workflows: { COLLECT: { name: "collect", className: "CollectWorkflow" } }. - A matching binding on
Cloudflare.Envinapps/<worker>/src/cloudflare-test.d.ts, typed with the Workflow’s params:COLLECT: Workflow<CollectParams>.
introspectWorkflowInstance from cloudflare:test watches one instance by id. Open it before you create the instance, dispose of it with await using, and wait on its status rather than on a timer. Disposing it deletes the instance, so scope it to the whole test: an instance id is free again the moment its introspector is disposed.
import { env, introspectWorkflowInstance } from "cloudflare:test";
await using instance = await introspectWorkflowInstance(env.COLLECT, "run-1");
await env.COLLECT.create({ id: "run-1", params: {} });
await instance.waitForStatus("complete");
expect(await instance.getOutput()).toEqual({ written: 3 });Test a duplicate instance id
A create under an id that already has an instance is refused. To test that refusal, hold the first instance’s introspector until the end of the test, and make the second create inside its scope:
await using instance = await introspectWorkflowInstance(env.COLLECT, "run-1");
await env.COLLECT.create({ id: "run-1", params: {} });
await instance.waitForStatus("complete");
await expect(env.COLLECT.create({ id: "run-1", params: {} })).rejects.toThrow(/already exists/);Dispose the introspector first, in a helper or an inner block, and the second create succeeds. Disposal deleted the instance, so there is no duplicate to refuse. A test written that way fails for a reason that has nothing to do with the code under test, and a check that a duplicate is accepted passes without proving anything.
Hold a Workflow step at a gate
Testing an overlap means stopping one run mid-step, starting the other, and letting the first go when the test says so. createGate from @pithy-sh/core/testing is that stop. A gate is a flag: one side calls open(), and the other waits on opened().
The step reaches the gate through a seam the test injects, such as the fetcher the Workflow calls. Use two gates per held run: held, which the step opens when it arrives, and release, which the test opens to let it go:
import { createGate } from "@pithy-sh/core/testing";
const held = createGate({ name: "first run held" });
const release = createGate({ name: "first run released" });
// In the fetcher the test injects, which the step calls:
held.open();
await release.opened();
// In the test:
await env.COLLECT.create({ id: "first", params: {} });
await held.opened();
// start the second run, assert on the overlap, then:
release.open();Open every release gate in a finally. Otherwise a failed assertion leaves a step waiting while the introspector is disposed. A wait that runs out throws an InternalError naming the gate rather than hanging: timeoutMs sets how long, 30,000 ms by default, and pollMs how often it checks, 5 ms by default.
Never await a promise the other side settles. A step must not await a promise the test settles, and the test must not await one a step settles. That rules out the obvious gate, a new Promise the test resolves.
The test and each step run in separate request contexts, and workerd does not count a promise another request will settle as pending work in the one waiting on it. A step parked on the test’s promise has nothing of its own pending, so workerd can cancel it as hung (“detected that your Worker’s code had hung”). Disposing the introspector then waits for a step that will never finish, the test times out, and the assertion that actually failed is never reported. Whether it fires depends on what else both sides have in flight, so a test that passes alone can hang in a busier suite.
createGate sidesteps it: opened() checks a plain flag on a timer of the waiting side’s own, so nothing either side awaits is settled by the other.
Idempotency deserves its own test
Anything carrying an idempotency reference — a ledger movement, a purchase projection, a seeded row — has a test worth writing: do it twice, assert the state is what it was after once.
That is the property the whole design rests on, and it is cheap to assert and expensive to discover missing.
The gates a scaffold ships with
Three, and CI needs all three:
| Script | Runs |
|---|---|
typecheck | The whole solution |
test | Both runtimes |
lint | The formatter and the kit’s lint safeguards |
The root TypeScript config is a solution file, and it has to be. A Worker program needs the Workers types and a browser program needs the DOM, and a program carrying both makes a byte array structurally incompatible with a buffer source — which breaks every crypto call in the kit’s own signing code. Keeping the two type worlds apart is the only arrangement that compiles.
One gap, stated rather than hidden: pithy worker add does not add the new Worker to the solution file. Add the reference yourself, or that Worker’s source is typechecked by nothing.
An Expo app’s screen tests are not in the root test. An app from pithy ui add react-native brings a vitest.config.ts of its own, and the root config leaves any such app out of its Node project, because a screen that imports react-native does not load in plain Node. Run the app’s own test script beside the root one, in CI too. React Native has what it runs.
Add pithy doctor to CI
pithy doctor --jsonIt exits non-zero when any Worker fails a check, and it catches things a unit test structurally cannot: a binding declared and not bound, a Workflow declared and never synced, a domain nothing routes, a capability composed without its prerequisites, a locale with gaps.
The unsynced Workflow is the one worth having. Its entire symptom is that nothing happens — no request fails, no log line appears, no probe goes red, and the cron simply never fires.
And the asset-routing check, if you have a front end
pithy ui sync --check --worker apiA shadowed route answers a 200 of the SPA shell with your handler never invoked — and no test suite of yours sees it, because tests call handlers directly and the asset router is never in the picture.
That is exactly the shape of bug that needs a check rather than a test.