test-badass
Skill1 starsChanged 3 months agoMITView on GitHub
Master, versatile test-generation and test-repair engine for this Bun + Hono + Drizzle ORM project, routing every testing request into one of four modes — (1) Spec-Driven TDD/RED: generate failing `.spec.ts`/`.e2e.spec.ts` files straight from a `docs/plans/*.md` plan doc before the target module exists, capturing business rules and error contracts as executable specs; (2) Test-After coverage backfill: analyze an existing module's branches/edge cases and write the missing tests without touching source; (3) Targeted layer testing: scope tightly to one layer (controller/service/repository/entity) on explicit request; (4) Test Refactor & Repair: diagnose and fix tests broken by a `bun test` failure after a refactor, distinguishing a legitimate contract change from a real regression rather than blindly editing assertions until green. All four modes share this project's Testing Trophy conventions (mostly integration, against a real ephemeral Postgres via Testcontainers), Bun's built-in `bun:test` runner, `spyOn` for the one unit-test exception, and a strict no-`any` policy. Use this whenever the user asks to write, generate, add, fix, backfill, or repair tests or test coverage for any module/service/repository/controller/entity — including "write tests for X from the plan", "this module has no tests yet", "just test the repository layer", "bun test is failing after I refactored Y", "cover the DELETE /books/{id} route", or when a newly-written or newly-edited module lacks a corresponding test file — even if the user doesn't name this skill or say "Hono"/"Drizzle" explicitly.
- Reads credentials
In this repository5 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- arch-auditSkill
- feature-flowSkill
- feature-planSkill
- gen-moduleSkill
The file
We split this skill into the rules it gives an agent
12 rules. About 0 are common, 4 are distinctive, and 8 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈4
Distinctive · estimate
This author's own choices. Worth a look.
8
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 74
Do not write a single line of test code before you understand the target completely:
- Distinctive: line 79
Look for an existing sibling test file first: If the module already has other test files, that file's conventions win over anything generic …
- Very specific: line 90
If bunfig.toml or tests/testcontainers-setup.ts is missing when you go looking for it, that's a real infra gap — say so and ask rather than …
- Very specific: line 119
Use bun test — Bun's built-in runner, no separate package.
- Very specific: line 121
No
any: Every fixture and stub must carry a real type. - Distinctive: line 139
Only reach here per Step 2's criteria.
- Very specific: line 182
Group fields of the same returned object together: If a use case/route returns one entity/DTO, assert its related fields in a single it() — …
- Very specific: line 190
Every collaborator a unit-tested target relies on is spyOn'd (or mock.module'd) with a real, typed return value.
- Very specific: line 192
No manually hand-rolled fake objects standing in for a spy where spyOn on the real singleton should have been used.
- Very specific: line 194
Every spyOn/mock.module is restored (afterEach(() => mock.restore())).
- Very specific: line 196
Run the new/changed spec scoped to its file (bun test path/to/file.spec.ts) to confirm it actually passes, not just compiles.
- Distinctive: line 198
If overwriting an existing test file, skim it first for hand-written tests worth preserving (e.g.
≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
test-badass — the testing engine for this stack
Why: the Testing Trophy, not the pyramid
This skill follows Kent C. Dodds's Testing Trophy: "Write tests. Not too many. Mostly integration." That motto corrects the traditional pyramid's unit-heavy default, and the reasoning matters more than the label:
- Static analysis (base). Biome (
bunx biome check) andtsc --noEmitalready catch typos, unused imports, and type errors before a single test runs — this layer is "free" only if the code you generate actually satisfies it. A generated test withanyin it, or that doesn't compile, has failed the cheapest layer there is. - Unit tests. Small, isolated logic — pure functions, mappers, domain-entity validation, error factories — verified with no test double, or with the one collaborator stubbed out. Useful, but narrow.
- Integration tests (the core — biggest layer). Multiple real units cooperating — a controller route invoking a service invoking a real repository against a real Postgres, the
@hono/zod-openapirequest-validation pipeline and the global error handler actually running. This is where most real bugs live (a wrongwhereclause, a DTO that doesn't actually reject what it should, an error that doesn't map to the contract it's supposed to). - E2E (top). Real browser/user-journey tests. Not applicable to this backend repo — integration is the ceiling of coverage here.
This stack pushes toward integration even harder than a DI framework would. service.ts hard-imports its repository directly — there's no container to swap a fake through. Mocking a service's repository calls means reaching for spyOn/mock.module rather than an elegant provider override, which is real friction. That friction is a signal, not an obstacle to route around: it's the Trophy's own argument for defaulting to integration.
Generated tests are only worth the tokens they cost if a human never has to rewrite them. Follow the reasoning below, not just the letter — if a target doesn't fit a pattern, adapt the pattern rather than forcing it.
Step 0 — Which mode are you in?
Every testing request fits one of four modes. Diagnose the mode first — it decides where you look for the truth about what the tests should assert (a plan doc, existing source, a git diff, or an existing test file) before any code gets written. Check in this order; the first match wins, except Mode 3, which is a scope filter that layers on top of whichever of 1/2/4 otherwise applies rather than replacing it (e.g. "just the repository layer, from the plan" is Mode 1 narrowed to one file).
| # | Mode | Trigger | Truth source |
| 4 | Refactor & Repair | bun test currently fails for a target whose source and tests both already exist (the user says tests broke, or you can see red output) | The diff between old and new source contract |
| 1 | Spec-Driven TDD (RED) | The request points at a docs/plans/*.md plan doc, and the target module doesn't exist yet under src/modules/<feature>/ (or the specific file being planned isn't written yet) | The plan doc's Decisions/Example sections |
| 3 | Targeted layer | The user names one specific layer explicitly ("just the controller", "repository tests for X") | Whatever Mode 1/2/4 would use, narrowed to that one file |
| 2 | Test-After (default) | Source exists, tests are missing or incomplete, nothing more specific is signaled | The existing source code itself |
Check Mode 4 first: a currently-broken test suite is an urgent, already-observable failure, not a backfill or planning task, even if the request is phrased generically ("fix the tests"). Check Mode 1 second, since a plan doc plus nonexistent source is unambiguous. Everything else defaults to Mode 2, which is where most of this skill's mechanics live — Modes 1, 3, and 4 each describe what's different about their situation and then point back into Mode 2 / the shared conventions below for the actual test-writing mechanics.
Mode 1 — Spec-Driven TDD (RED phase 🔴)
The plan doc (built via docs/plans/TEMPLATE.md's structure, see the feature-plan skill) is the spec. Read its Current State, Decisions, and worked Example section — that's where business rules, error codes, and request/response shapes live before any implementation exists. Generate *.service.spec.ts and *.controller.e2e.spec.ts (or whichever files the plan's scope calls for) that encode every rule the plan states as a real, typed test — not prose restated as a comment.
The catch that makes this mode different from Mode 2: there's no real repository.ts/entity.ts/dto.ts to read return types from (Step 1's normal first move), because nothing has been implemented yet. Build fixtures and expected shapes directly from the plan's Example section instead, and say plainly which types you're inventing to match the plan versus which ones you're inferring from an already-decided shared convention (e.g. DomainError's shape, or the timestamp/ID conventions in docs/02-clean-architecture.md/docs/06-database-migrations.md — those are fixed regardless of the specific module).
These tests are expected to fail to compile or run until gen-module (or hand-written code) implements the target — that's the point of RED, not a mistake to fix. Don't water down a test's assertions just to make it type-check against nothing; write it against the shape the plan actually describes, hand it back, and say clearly that it's red by design pending implementation. If the plan doc has an unresolved Open Questions entry that the test would need answered to be written correctly, stop and say so rather than guessing — that's a gap in the plan, not something to paper over with an assumption baked silently into a fixture.
See references/spec-driven-tdd.md for a full worked example (reading a plan's Example section, deriving fixtures, and what a "correctly red" test file looks like).
Mode 2 — Test-After (Coverage Backfill)
The default mode, and where the shared mechanics below (Steps 1–9) live in full. Source exists in src/modules/<feature>/; tests are missing entirely or don't cover everything the code does. Read the target and its collaborators (Step 1), enumerate branches/boundary conditions/edge cases the existing tests don't hit, and write only what's missing — never touch the source file to make a test easier to write; if the code seems genuinely wrong while backfilling, say so and stop rather than silently changing it.
A missing-coverage audit means actually reading every conditional, every early return, every thrown DomainError, and every Zod refinement in scope — not just mirroring the happy path that's easiest to imagine. If a sibling test file already covers some cases, read it first (Step 1.4) so you add to it rather than duplicating.
Mode 3 — Targeted Testing (Layer Focus)
Not a separate way of writing tests — a scope restriction on whichever of Modes 1/2/4 the situation otherwise calls for. If asked for "just the repository tests," don't also touch the service or controller layer's coverage even if it's thin, and don't expand scope to "the whole module" unprompted. The existing per-layer guidance still applies fully within that one layer:
controller.ts→ integration only, via the router's own.request()(see Step 5) — there is no unit-testable form (see Step 2 below).service.ts→ integration by default; unit only to force an edge case per Step 2's three bullets.repository.ts→ integration against the real (Testcontainers) Postgres — query correctness is the whole point, a stub can't prove awhereclause is right.entity.ts/dto.ts→ usually pure unit tests (Zod.safeParse()behavior, mapper functions) — see Step 6's archetype A.
Mode 4 — Test Refactor & Repair
Triggered by a red bun test for a target whose source just changed. The job is not "make it green again" — a test that's edited until it passes without checking whether the new behavior is actually correct defeats the entire purpose of having it. Work in this order:
- Read the actual failure output first — the assertion that failed and why, not just "it's red."
- Diff the source, not just the test.
git diff(or read old vs. new) the file(s) the failing test exercises. Every failure falls into one of two categories, and they get opposite treatment:- The contract legitimately changed (a field renamed, an error code updated, a new required field, a status code intentionally changed) — the test's assumptions are stale, not the code. Update the assertions/mocks/fixtures to match the new, correct contract. Cross-check against the module's
docs/plans/*.mdhistory or the user's stated intent for the refactor if it's not obvious from the diff alone — don't assume a diff is "intentional" just because it compiles. - The code has a real regression (the diff introduces a bug; the old, still-correct behavior is what broke) — the test caught something real. Do not edit the assertion to match the broken behavior. Report the regression and stop; fixing source code is outside this skill's job (see Step 9's boundary), but silently "fixing" the test to hide a real bug is worse than doing nothing.
- The contract legitimately changed (a field renamed, an error code updated, a new required field, a status code intentionally changed) — the test's assumptions are stale, not the code. Update the assertions/mocks/fixtures to match the new, correct contract. Cross-check against the module's
- Preserve coverage, don't delete it. If a case genuinely no longer applies (the behavior it tested was intentionally removed), say so explicitly and remove that one
it()— don't delete a whole file's worth of cases because one broke, and don't comment out a failing assertion instead of resolving it one way or the other. - Re-run the target file (
bun test path/to/file) after each fix to confirm it's actually green, not just plausible-looking.
See references/refactor-and-repair.md for a worked example distinguishing these two cases from the same git diff.
Step 1 — Read before writing (Modes 2, 3, 4; adapted for Mode 1 above)
Do not write a single line of test code before you understand the target completely:
- Read the target (the
service.tsuse case,repository.tsmethod,controller.tsroute, orentity.tsvalidator in scope) and every file it imports from within its own module. - Read what each collaborator actually returns. For a service, open the
repository.tsit calls and read the real return types on<module>Repository's methods. For a repository, read<module>.schema.ts(the Drizzle table) and<module>.entity.ts(whattoEntity()maps rows into). - Read the
entity.tsanddto.tsZod schemas referenced in the target's signature so constructed fixtures satisfy them by real values, not by casting oras-ing into shape. - Look for an existing sibling test file first. If the module already has other test files, that file's conventions win over anything generic below — match its import style, fixture setup, and DB-reset strategy exactly.
- Check
docs/05-testing-strategy.mdand this skill, but verify against what's actually in the repo (package.json,bunfig.toml, the actual contents oftests/modules/<feature>/) before trusting either as current.
The Testcontainers harness — no more "does a test DB exist?" guesswork
bunfig.toml's [test] preload loads tests/testcontainers-setup.ts once, before any test file is imported: it starts an ephemeral Postgres via Testcontainers, points DATABASE_URL at it, runs the real migrations from ./migrations, and tears the container down in a global afterAll once the whole run finishes. This means:
- No
.env.testto create or check for. The container's connection string overridesprocess.env.DATABASE_URLbeforesrc/configs/env.ts'ssafeParseever runs — importingservice.ts/repository.tsin a test file just works, with a real database behind it. - Every test run gets a fresh, empty (post-migration) database.
tests/db-context.ts'sresetTestDb()still truncates between individual tests — Testcontainers changes where the database lives, not the per-test reset strategy. @/configs/db'sdbsingleton is already correctly wired by the time any test file imports it (directly or via a module'srepository.ts) — never build a second, ad hoc connection in a test file. If you find yourself writing new connection-setup code, stop; it already exists.
If bunfig.toml or tests/testcontainers-setup.ts is missing when you go looking for it, that's a real infra gap — say so and ask rather than fabricating a workaround per test file.
Step 2 — Choosing a layer: default to integration
The Trophy's fat middle is deliberate: most real bugs live in the seams between units, and stubbing every collaborator removes exactly those seams from the test. Default to an integration test whenever the target's job is to coordinate — a controller route invoking a service invoking a repository, a service whose correctness depends on a real query, anything that goes through @hono/zod-openapi's request validation or the global error handler. This covers the large majority of service.ts, repository.ts, and controller.ts files.
Controllers structurally cannot be unit tested in this codebase. Route handlers stay inline (never extracted into a named function) so Hono's type inference for c.req.valid(...) keeps working — there is no standalone function to call directly. The only way to exercise a route at all is through the router itself (.request(), see Step 5), which is inherently an integration test.
Reach for a unit test only when the thing under test is genuinely isolated:
- A pure function whose entire contract is input → output: a mapper, a domain-entity Zod schema's
.safeParse()behavior, an error factory, agenerateId()-style utility. - A method with many branch/edge-case permutations where seeding real rows per case would be slow and wouldn't add signal beyond the branch logic itself.
- Forcing a failure mode real infrastructure can't easily produce on demand.
If you're unsure which bucket a case falls into, ask: "if I stubbed this collaborator, would the test still tell me the target is wired correctly, or only that it correctly calls a function I made up the return value for?" The former can be a unit test. The latter is the exact smell the Trophy exists to correct — write the integration test instead.
Step 3 — Where the file goes and what it's called
Tests live in tests/, a sibling of src/, mirroring the module structure — not colocated with the source: tests/modules/<feature>/. Files stay flat, always, a deliberate exception to src/modules/'s nest-past-2 rule.
- Unit:
tests/modules/books/books.service.spec.ts,.repository.spec.ts,.entity.spec.ts— same base name as the source,.spec.tssuffix. - Integration:
tests/modules/books/books.service.e2e.spec.ts,.controller.e2e.spec.ts— same base name,.e2e.spec.tssuffix.
Get the separator right. bun test only auto-discovers filenames containing .test, .spec, _test_, or _spec_ — books.controller.e2e-spec.ts (hyphen before spec) is silently never run, with no warning. .e2e.spec.ts (dot before spec) is the form that's actually discovered.
@/* alias imports inside a test file resolve the same regardless of where the test physically lives. If a sibling test file already exists using a different convention, match it instead (Step 1.4).
Step 4 — Framework rules (apply to every layer, every mode)
- Use
bun test— Bun's built-in runner, no separate package. - Always explicitly import
describe,it,expect,beforeEach,afterEach,mock,spyOn, etc. from'bun:test'— these are named exports, not ambient globals. - No
any. Every fixture and stub must carry a real type. If a return type is a union, type the fixture accordingly rather than widening it away. @/*alias only, one level of relative max — a hard Biome lint rule (noRestrictedImportson../**/*).- Build fixtures as real typed values against the actual Zod-inferred types (
const input: CreateBookDto = {...}), not inline untyped literals.
Step 5 — Integration tests: the core layer, reach for this first
Nothing in the layer under test is stubbed. Pick the shape based on what you're actually verifying:
- HTTP-level, via the module's own controller router — required whenever request validation, the error contract, or exact response status/shape are part of what's under test. Call
.request()directly on the exported router — Hono routers are Fetch-API-native, no supertest needed. - Repository-level, real
db, no HTTP — enough when verifying query correctness.createBookRepository(testDb)takes an injecteddbdirectly; import the realdbfrom@/configs/db(already pointed at the Testcontainers instance by the preload harness — see Step 1) rather than building a second connection. - Service-level, real
db, no HTTP — for verifying coordination logic against real data when the HTTP pipeline isn't the point. Sinceservice.tshard-imports its repository singleton, this relies on the app's realdbalready pointing at the test database for the run — which the Testcontainers harness guarantees.
Remember IDs are app-generated (generateId()) — fixtures inserted directly (bypassing a service's create* use case) still need a real id supplied, not a DB default.
See references/integration-test-example.md for a full worked example of all three shapes.
Step 6 — Unit tests: the exception, not the default
Only reach here per Step 2's criteria. There is no DI container and no class to mock through — a module's repository is a plain typed object:
- Pure logic, no collaborator at all — call the function directly.
- Stubbing the one collaborator a service needs, to force an edge case —
spyOn(bookRepository, 'findByIsbn')(imported directly) gives a fully-typed mock scoped to that one method. Restore it afterward (mock.restore()inafterEach). - Preventing a whole module's top-level side effects (rare) —
mock.module('@/configs/db', () => ({ db: fakeDb })), which must run before the mocked module is first imported anywhere in the file (ESM import hoisting) — the same ordering reasoningtests/testcontainers-setup.tsrelies on for its own dynamic import (Step 1).
import { describe, it, expect, spyOn, afterEach, mock } from 'bun:test';
import { createBook } from '@/modules/books/books.service';
import { bookRepository } from '@/modules/books/books.repository';
import type { CreateBookDto } from '@/modules/books/books.dto';
afterEach(() => {
mock.restore();
});
describe('createBook()', () => {
describe('GIVEN a book with that ISBN already exists', () => {
it('THEN should throw BOOK_DUPLICATE_ISBN without inserting', async () => {
const input: CreateBookDto = { title: 'Dune', author: 'Frank Herbert', isbn: '9780441172719' };
spyOn(bookRepository, 'findByIsbn').mockResolvedValue(/* existing Book fixture */);
const insertSpy = spyOn(bookRepository, 'insert');
await expect(createBook(input)).rejects.toThrow();
expect(insertSpy).not.toHaveBeenCalled();
});
});
});See references/unit-test-example.md for the pure-logic archetype and a fuller worked version of the stubbed-collaborator case.
Step 7 — Structure every test Given-When-Then
- Top-level
describe: the file's subject, e.g.describe('createBook()', ...)ordescribe('POST /books', ...). - Second-level
describe, if there's more than one precondition: the specific case, e.g.describe('GIVEN a book with that ISBN already exists', ...). - Context
describe: prefix withGIVEN(a precondition/state) orWHEN(an input/action) — whichever reads more naturally. itblocks: prefix withTHEN, stating the observable outcome.
Step 8 — One assertion strategy decision per it(): group or isolate?
- Group fields of the same returned object together. If a use case/route returns one entity/DTO, assert its related fields in a single
it()— one failing test shows the whole broken shape, not five tests each showing one field out of context. - Isolate independent side effects into separate
it()blocks. If the target also writes to a second table, calls another module's repository, or performs an unrelated action, each is its ownit()— bundling unrelated systems means one broken side effect hides the pass/fail signal for the others.
In short: group when failure in one place is expected to explain failure in the others (same object); isolate when the things being asserted are causally unrelated.
Step 9 — Before you finish, check
- Mode and layer choice are both justified — you can name which row of Step 0's table you're in, and, if you wrote a unit test, which of Step 2's three bullets justified it.
- Every collaborator a unit-tested target relies on is
spyOn'd (ormock.module'd) with a real, typed return value; an integration test uses the realdb/router, not stubs. - No
anyanywhere, including an unspecified generic that widens toany. - No manually hand-rolled fake objects standing in for a spy where
spyOnon the real singleton should have been used. - File lands in
tests/modules/<feature>/, never colocated insrc/, never nested further, with the name/suffix from Step 3. - Every
spyOn/mock.moduleis restored (afterEach(() => mock.restore())). - Run the static analysis layer —
bunx biome check <file>andbunx tsc --noEmit— before handing it back. - Run the new/changed spec scoped to its file (
bun test path/to/file.spec.ts) to confirm it actually passes, not just compiles. - Mode 4 only: confirm you diagnosed contract-change vs. regression (Mode 4, step 2) before touching any assertion — don't hand back a "fixed" test without being able to state which category it was.
- If overwriting an existing test file, skim it first for hand-written tests worth preserving (e.g. a regression test tied to a specific past bug) — don't silently delete coverage that isn't obviously superseded.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

