Test a NestJS Drizzle CRUD service
Test a NestJS Drizzle CRUD service against real SQL in memory with PGlite, or unit test it with TestCrudFactory and a Jest mock database.
To test a NestJS Drizzle CRUD service, boot it through DrizzleCrudModule against PGlite, an in-memory Postgres, so every filter, soft delete and constraint runs as real SQL with no server or container. For narrow unit tests, the package also exports TestCrudFactory, which builds the service on a Jest mock database that runs no SQL, and BaseCrudSpecHelper, a base class around it.
A mock cannot check your SQL
The mock database accepts any query, so it cannot catch a wrong column key, a bad cast or a constraint violation. The package added its own PGlite suite after mocked tests let real bugs through. Use the mock for logic in your service, and PGlite for anything that touches the database.
How do I test against a real database?
Install PGlite and the Nest testing module
pnpm add @electric-sql/pglite @nestjs/testing -DCreate the tables in memory
Each test gets its own database, so tests never depend on each other's rows:
import { PGlite } from '@electric-sql/pglite';
import { drizzle } from 'drizzle-orm/pglite';
export async function freshDb() {
const client = await PGlite.create();
await client.exec(`
CREATE TABLE users (
id serial PRIMARY KEY,
name varchar(100) NOT NULL,
email varchar(255) NOT NULL UNIQUE,
created_at timestamp NOT NULL DEFAULT now(),
updated_at timestamp NOT NULL DEFAULT now(),
deleted_at timestamp
);
`);
return { client, db: drizzle(client) };
}If you use drizzle-kit, you can run your migrations against the client instead of writing the DDL by hand.
Build the service through the module
Register the service the way your app does, with forRoot and forFeature, so the test also covers the config merge:
import { Test, type TestingModule } from '@nestjs/testing';
import type { PGlite } from '@electric-sql/pglite';
import { DrizzleCrudModule, EntityNotFoundException } from '@avytrix/nestjs-drizzle-crud';
import { users } from '../src/db/schema';
import { UsersService } from '../src/users/users.service';
import { freshDb } from './db';
describe('UsersService', () => {
let client: PGlite;
let moduleRef: TestingModule;
let service: UsersService;
beforeEach(async () => {
const fresh = await freshDb();
client = fresh.client;
moduleRef = await Test.createTestingModule({
imports: [
DrizzleCrudModule.forRoot({ dialect: 'postgresql', db: fresh.db }),
DrizzleCrudModule.forFeature([{ service: UsersService, table: users }]),
],
}).compile();
service = moduleRef.get(UsersService);
});
afterEach(async () => {
await moduleRef.close();
await client.close();
});
it('creates and finds a user', async () => {
const user = await service.create({ name: 'Ada', email: 'ada@example.com' });
const found = await service.find(user.id);
expect(found?.email).toBe('ada@example.com');
});
it('hides soft-deleted rows from findAll', async () => {
const user = await service.create({ name: 'Ada', email: 'ada@example.com' });
await service.softDelete(user.id);
const { total } = await service.findAll({});
expect(total).toBe(0);
});
it('throws EntityNotFoundException when updating a missing row', async () => {
await expect(service.update(999, { name: 'X' })).rejects.toBeInstanceOf(
EntityNotFoundException,
);
});
});The module does not close a db you pass in, so close the PGlite client yourself in afterEach.
What does the package export for tests?
Two classes, both from nestjs-drizzle-crud (src/test-utils). Both call the global jest, so they only work inside Jest.
| Export | Method | Returns |
|---|---|---|
TestCrudFactory | createMockDb() | A stub db whose select, insert, update, delete, transaction and chain methods (from, where, limit, offset, orderBy, values, set, returning) are jest.fn(). Runs no SQL. |
createMockTable() | A plain object with the keys id, name, email, created_at, updated_at, deleted_at. Takes no arguments. | |
createMockEntity(overrides?) | A row with id: 1, a name, an email and both timestamps, merged with your overrides. | |
createTestService(Service, db, table, config?) | A service built directly, without Nest DI, with the config below. | |
BaseCrudSpecHelper | constructor and scenario methods | A base class that builds a service with TestCrudFactory and returns canned find, create, update, delete and findAll scenarios that stub the mock db. |
createTestService builds this config, then spreads your config over it:
dialectOptional"postgresql" | "mysql" | "sqlite"
Defaults to "postgresql"
primaryKeyOptionalstring
Defaults to "id"
softDeleteOptional{ enabled, column }
Defaults to { enabled: true, column: "deleted_at" }
timestampsOptional{ createdAt, updatedAt }
Defaults to { createdAt: "created_at", updatedAt: "updated_at" }
paginationOptional{ defaultLimit, maxLimit }
Defaults to { defaultLimit: 20, maxLimit: 100 }
sqlOptionalobject
Defaults to { caseSensitive: false, useReturning: true, ... }
The spread is shallow: passing softDelete: { column: 'deletedAt' } replaces the whole object, so also pass enabled: true.
How do I unit test with the mock database?
Stub the chain the method calls, then assert on the result and the calls. create runs db.insert(table).values(row).returning():
import { TestCrudFactory } from '@avytrix/nestjs-drizzle-crud';
import { UsersService } from '../src/users/users.service';
it('returns the inserted row', async () => {
const mockDb = TestCrudFactory.createMockDb();
const row = TestCrudFactory.createMockEntity({ name: 'Ada' });
mockDb.insert.mockReturnValue({
values: jest.fn().mockReturnThis(),
returning: jest.fn().mockResolvedValue([row]),
});
const service = TestCrudFactory.createTestService(
UsersService,
mockDb,
TestCrudFactory.createMockTable(),
);
await expect(service.create({ name: 'Ada', email: 'test@example.com' })).resolves.toEqual(row);
expect(mockDb.insert).toHaveBeenCalledTimes(1);
});You can pass your real Drizzle table instead of the mock table. Then set softDelete and timestamps to its keys, or turn them off: the service checks them when it is built and throws if one is missing. With a real table, logic that reads column types works without a database, for example service.idKind() and service.parseId('12').
How do I test hooks?
Hooks are protected methods on the service. Spy on one and run the method that calls it:
it('passes the input to beforeCreate', async () => {
const spy = jest.spyOn(service as any, 'beforeCreate');
await service.create({ name: 'Ada', email: 'ada@example.com' });
expect(spy).toHaveBeenCalledWith({ name: 'Ada', email: 'ada@example.com' });
});Or override the hook in a test-only subclass and register that subclass in forFeature:
import type { CreateUserDto } from '../src/users/dto/create-user.dto';
import { UsersService } from '../src/users/users.service';
export class TestUsersService extends UsersService {
protected async beforeCreate(data: CreateUserDto) {
return { ...data, name: data.name.trim() };
}
}How do I check the merged config?
The service keeps its merged config in the protected config property. After building it through the module, read it in a test:
expect((service as any).config.softDelete).toEqual({ enabled: true, column: 'deleted_at' });Common questions
Yes. PGlite runs Postgres in memory inside the test process, so the real module and real SQL run with no server, container or credentials.
No. createMockDb calls the global jest to build its mock functions, so it only works inside a Jest test file.
No. It takes no arguments and returns a fixed object with id, name, email, created_at, updated_at and deleted_at. Pass your real table to createTestService instead if you need its columns.
The service checks its soft-delete and timestamp keys when it is built. Set them to keys your table has, or turn them off in the config you pass.
Next steps
API reference
Every service method and its signature.
Errors and status codes
Which exception each failure throws, to assert in tests.
AI agents and the MCP server
Give your coding agent the package rules and docs.
Drizzle forFeature in NestJS
Drizzle forFeature in NestJS binds each CRUD service to its table and merges per-entity config over the project defaults from forRoot, one level deep.
NestJS Drizzle MCP server for AI agents
Run the NestJS Drizzle MCP server with npx so Claude Code, Cursor or Copilot can read the package docs, and add the AGENT.md rules file to your repo.