Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท Testing and Deployment

Testing Prisma Code

Test code that uses Prisma with unit tests and fakes, integration tests against a real test database, per-test cleanup by rollback or truncate, and seeded fixtures with node:test.

Tests that touch a database are slower and trickier than pure-function tests, but skipping them is how bugs reach production. There are two layers worth having: unit tests that replace the database with a fake so business logic can be tested instantly, and integration tests that run against a real database so queries, constraints and migrations are actually exercised. This lesson explains both and shows how to keep tests independent.

Prisma code is read-only here. The TryIts are labelled stand-ins using node:test-style checks and node:sqlite.

Layer 1: unit tests with a fake client

Keep business rules in functions that receive the database client instead of importing a global one (dependency injection). Then tests can pass a fake:

TypeScript
// src/signup.ts
import type { PrismaClient } from './generated/client';

export async function signUp(db: Pick<PrismaClient, 'user'>, email: string) {
  const existing = await db.user.findUnique({ where: { email } });
  if (existing) throw new Error('Email already registered');
  return db.user.create({ data: { email } });
}

The fake only needs the methods the function uses. Libraries such as vitest-mock-extended or jest-mock-extended can build deep mocks automatically, but a hand-written fake is often clearer.

Node.js Stand-in: unit test with an injected fake

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Unit tests with fakes are fast, but they only prove your logic calls the client the way you expect. They cannot prove the query is correct, the unique constraint exists or the migration works. A mock that returns whatever you tell it can pass while production fails.

Layer 2: integration tests with a real database

Run tests against the same database engine as production (PostgreSQL in production means PostgreSQL in tests). Options:

  • A dedicated test database on your machine, created with prisma migrate deploy (or migrate reset) before the suite. Set DATABASE_URL to it through .env.test.
  • A disposable container started by the test runner (Docker, Testcontainers).
  • SQLite in memory only if production also uses SQLite; behavior differs across engines (case sensitivity, JSON, transactions), so it is a poor stand-in for PostgreSQL.

Never point tests at a development or production database. Add a guard that refuses to run unless the URL contains test.

Keeping tests independent

Tests must not depend on each other's leftovers. Three strategies, from simplest to fastest:

  1. Truncate between tests. TRUNCATE ... RESTART IDENTITY CASCADE on PostgreSQL, run in beforeEach. Simple and reliable; slower with many tables.
  2. Delete in dependency order. deleteMany on children first, then parents, using a helper.
  3. Roll back. Start a transaction per test, run it inside, roll back at the end. It is very fast, but the code under test must use the transaction client you hand it (another reason for dependency injection), and tests that use their own transactions need savepoints.
TypeScript
beforeEach(async () => {
  await prisma.$executeRaw`TRUNCATE TABLE "Post", "User" RESTART IDENTITY CASCADE`;
});
Node.js Stand-in: rollback isolation per test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last test is something no mock can prove: the database itself rejects duplicates.

What to test in integration

  • Queries with filters, ordering and pagination return the right rows.
  • Constraints: uniqueness, foreign keys, required fields, cascades.
  • Transactions really roll back when a step fails.
  • Your raw SQL returns the expected shape.
  • The migration history applies cleanly from an empty database (run migrate deploy in CI against a fresh one).

Fixtures and factories

Write small helper functions that create valid rows with overridable defaults:

TypeScript
export const makeUser = (db, overrides = {}) =>
  db.user.create({ data: { email: `u${Math.random().toString(36).slice(2)}@example.com`, ...overrides } });

Prefer a factory per test over one giant shared seed: each test reads top to bottom and states what it needs. Use a fixed seed or counters rather than Math.random() if you need reproducible failures.

Speed and CI

Run the integration suite serially against one database, or give each worker its own database (suffix with the worker number) to parallelize. In CI start the database as a service container, run npx prisma migrate deploy, npx prisma generate, then the tests (deployment lesson shows the pipeline).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does dependency injection of the Prisma client allow?

    When functions receive the client as a parameter, tests choose what to pass.
  2. 2. Which test can prove a unique constraint exists?

    Only the real database enforces constraints, so only a test using it can verify them.
  3. 3. Why should tests use the same database engine as production?

    A passing test on a different engine can hide a failure in production.
  4. 4. What is a benefit of rolling back a transaction after each test?

    Rollback discards everything the test wrote, so the next test starts from the same state.

Summary

  • Inject the client so logic can be unit tested with fakes and integration tested with a real client.
  • Fakes prove logic; only a real database proves queries, constraints and migrations.
  • Use the production engine, a dedicated test database and a guard against wrong URLs.
  • Isolate tests by truncating, deleting in order, or rolling back per test.
  • Build data with small factories; run migrate deploy in CI against a fresh database.

Next: Deploying Prisma Apps