That bug shipped on a Friday. A missing validation on the POST /orders endpoint was
accepting negative quantities — and by Monday, the database had 200 orders with
quantity: -1. Three hours of cleanup, one very awkward call with the client.
We had manual QA. We had staging. We didn't have tests.
That was the last time.
This post walks through test-first development in a NestJS backend — using Jest,
Supertest, and an in-memory MongoDB instance. Not theory. Working code, from red to green.
Why Test-First, Not Test-After
Writing tests after the fact is archaeological work. You reverse-engineer intent from
implementation, and you unconsciously write tests that match what the code does rather
than what it should do.
Writing the test first forces three things:
- You define the contract before the implementation
- You can't accidentally test implementation details
- Failing tests prove your tests actually work
The cost is front-loaded. The savings compound.
Setup
pnpm add -D jest @types/jest ts-jest supertest @types/supertest
pnpm add -D @nestjs/testing mongodb-memory-server mongoose @nestjs/mongooseConfigure Jest in package.json:



