# Seeding and Testing with a Real Database — Prisma / TypeORM / Sequelize

Source: https://www.skillbyai.com/en/orms/or-testing-seeding

> Seed predictable data, run tests against an isolated database, and reset state between tests without slowing the suite down.

## Test the SQL, not a mock of it

Mocking the ORM in unit tests checks that you *called* `findMany`, not that the query returns the right rows. Bugs in filters, joins and constraints only show up against a real database, so most teams run **integration tests** against a dedicated test database, often started in Docker. The recipe has three parts. **Schema**: apply migrations before the suite (`prisma migrate deploy`, `migration:run`, `db:migrate`) so tests use the same schema as production. **Seed data**: a script inserts known rows; Prisma has `prisma db seed` which runs a seed command you configure, Sequelize CLI has seeders run with `db:seed:all`, and TypeORM projects usually write a small seed script. **Isolation**: each test must start from a known state, either by truncating tables before each test or by wrapping each test in a transaction that is rolled back. Never point tests at a shared development or production database.

## A small, idempotent Prisma seed

Using `upsert` means running the seed twice does not create duplicates or fail on the unique email.

```ts
// prisma/seed.ts
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();

async function main() {
  for (const [email, name] of [['asha@example.com', 'Asha'], ['ravi@example.com', 'Ravi']]) {
    await prisma.user.upsert({ where: { email }, update: {}, create: { email, name } });
  }
}

main()
  .catch((e) => { console.error(e); process.exitCode = 1; })
  .finally(() => prisma.$disconnect());
```

## Truncate in the right order, or cascade

Deleting `users` before `posts` fails on the foreign key. Either delete children first, or on PostgreSQL use `TRUNCATE ... RESTART IDENTITY CASCADE` through a raw query in your test setup. Restarting identities also keeps generated IDs predictable across runs.

**Quiz:** Why are integration tests against a real test database preferred over mocking the ORM for query logic?

- [ ] Mocks are not allowed in Node.js test runners
- [ ] Real databases are always faster than mocks
- [x] A mock cannot catch wrong filters, joins or constraint violations that only the database evaluates
- [ ] ORMs cannot be imported in test files

*Answer:* A mock cannot catch wrong filters, joins or constraint violations that only the database evaluates. The bug is usually in what the SQL does. Only executing it against a real database proves the filter, join or constraint behaves as intended.
