Testing in NestJS
Dependency injection pays off most in tests. Because every class receives its dependencies, a test can build a small slice of the app with fake providers — no database, no network. Nest projects come with Jest configured and the @nestjs/testing package, which creates a mini DI container just for the test.
Three levels of tests
| Level | Builds | Example | File convention |
|---|---|---|---|
| unit | one class, dependencies faked | CatsService.create rejects duplicate names |
cats.service.spec.ts next to the code |
| integration | a module with some real providers | controller + service with an in-memory repository | *.spec.ts |
| end-to-end (e2e) | the whole app over HTTP | POST /cats returns 201 |
test/*.e2e-spec.ts |
npm run test # unit tests (jest)
npm run test:e2e # e2e tests (jest + supertest)
npm run test:cov # coverage report PASS src/cats/cats.service.spec.ts
PASS src/cats/cats.controller.spec.ts
Test Suites: 2 passed, 2 total
Tests: 7 passed, 7 total
Snapshots: 0 total
Time: 2.41 s
Unit-testing a service with Test.createTestingModule
// src/cats/cats.service.spec.ts
import { Test } from '@nestjs/testing';
import { ConflictException } from '@nestjs/common';
import { CatsService } from './cats.service';
import { CatsRepository } from './cats.repository';
describe('CatsService', () => {
let service: CatsService;
const repo = {
findByName: jest.fn(),
insert: jest.fn(),
};
beforeEach(async () => {
jest.resetAllMocks();
const moduleRef = await Test.createTestingModule({
providers: [
CatsService,
{ provide: CatsRepository, useValue: repo }, // fake instead of the real repository
],
}).compile();
service = moduleRef.get(CatsService);
});
it('creates a cat when the name is free', async () => {
repo.findByName.mockResolvedValue(null);
repo.insert.mockResolvedValue({ id: 1, name: 'Mochi', age: 3 });
await expect(service.create({ name: 'Mochi', age: 3 })).resolves.toEqual({ id: 1, name: 'Mochi', age: 3 });
expect(repo.insert).toHaveBeenCalledWith({ name: 'Mochi', age: 3 });
});
it('rejects a duplicate name', async () => {
repo.findByName.mockResolvedValue({ id: 7, name: 'Mochi', age: 5 });
await expect(service.create({ name: 'Mochi', age: 3 })).rejects.toBeInstanceOf(ConflictException);
expect(repo.insert).not.toHaveBeenCalled();
});
});| API | Purpose |
|---|---|
Test.createTestingModule({...}) |
declare the providers/controllers/imports under test |
.overrideProvider(X).useValue(fake) |
replace a provider coming from an imported module |
.overrideGuard(AuthGuard).useValue({ canActivate: () => true }) |
bypass auth in tests |
.compile() |
build the container (resolves all dependencies) |
moduleRef.get(X) |
fetch an instance |
The same idea without Jest
There's nothing magic about it: a test constructs the class with fakes, calls a method and checks the outcome. Here is the service and its two tests in plain TypeScript, using a "spy" that records calls:
class ConflictException extends Error { readonly status = 409; }
type Cat = { id: number; name: string; age: number };
interface CatsRepository {
findByName(name: string): Promise<Cat | null>;
insert(data: Omit<Cat, 'id'>): Promise<Cat>;
}
class CatsService {
constructor(private readonly repo: CatsRepository) {}
async create(data: Omit<Cat, 'id'>): Promise<Cat> {
if (await this.repo.findByName(data.name)) throw new ConflictException(`${data.name} already exists`);
return this.repo.insert(data);
}
}
function fakeRepo(existing: Cat | null) {
const calls: unknown[] = [];
const repo: CatsRepository = {
findByName: async () => existing,
insert: async (data) => { calls.push(data); return { id: 1, ...data }; },
};
return { repo, calls };
}
async function it(name: string, fn: () => Promise<void>) {
try { await fn(); console.log('✓', name); } catch (e) { console.log('✗', name, '-', (e as Error).message); }
}
function expectEqual(actual: unknown, expected: unknown) {
if (JSON.stringify(actual) !== JSON.stringify(expected)) {
throw new Error(`expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
}
}
await it('creates a cat when the name is free', async () => {
const { repo, calls } = fakeRepo(null);
const cat = await new CatsService(repo).create({ name: 'Mochi', age: 3 });
expectEqual(cat, { id: 1, name: 'Mochi', age: 3 });
expectEqual(calls.length, 1);
});
await it('rejects a duplicate name', async () => {
const { repo, calls } = fakeRepo({ id: 7, name: 'Mochi', age: 5 });
const error = await new CatsService(repo).create({ name: 'Mochi', age: 3 }).catch((e) => e);
expectEqual(error instanceof ConflictException, true);
expectEqual(calls.length, 0);
});
await it('this one is wrong on purpose', async () => {
const { repo } = fakeRepo(null);
const cat = await new CatsService(repo).create({ name: 'Pixel', age: 1 });
expectEqual(cat.age, 2);
});✓ creates a cat when the name is free
✓ rejects a duplicate name
✗ this one is wrong on purpose - expected 2, got 1
Test.createTestingModule does the new CatsService(repo) part for you — which matters once a class has five dependencies, each with their own.
End-to-end tests
E2E tests boot the real application module and send HTTP requests with supertest. Override only what talks to the outside world:
// test/cats.e2e-spec.ts
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import request from 'supertest';
import { AppModule } from '../src/app.module';
import { CatsRepository } from '../src/cats/cats.repository';
import { InMemoryCatsRepository } from './in-memory-cats.repository';
describe('Cats (e2e)', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
.overrideProvider(CatsRepository)
.useClass(InMemoryCatsRepository)
.compile();
app = moduleRef.createNestApplication();
app.useGlobalPipes(new ValidationPipe({ whitelist: true })); // same setup as main.ts
await app.init();
});
afterAll(() => app.close());
it('POST /cats creates a cat', () =>
request(app.getHttpServer())
.post('/cats')
.send({ name: 'Pixel', age: 1 })
.expect(201)
.expect(({ body }) => expect(body).toMatchObject({ name: 'Pixel', age: 1 })));
it('POST /cats validates the body', () =>
request(app.getHttpServer()).post('/cats').send({ name: '' }).expect(400));
});Note: Anything configured only in
main.ts(global pipes, filters, prefixes) is not part ofAppModule, so e2e tests must repeat it — or you register those globals asAPP_PIPE/APP_FILTER/APP_GUARDproviders inside a module, and the tests pick them up automatically.
Tips for testable Nest code
| Tip | Why |
|---|---|
| depend on abstractions (a repository class or token), not on ORMs directly | easy to fake |
| keep controllers thin | most logic gets unit-tested in services |
one beforeEach building a fresh module |
no state leaks between tests |
| test guards and pipes as plain classes too | new RolesGuard(reflector).canActivate(ctx) |
Test yourself
How do you replace a real repository with a fake in a Nest unit test?
- Edit the module file
{ provide: CatsRepository, useValue: fakeRepo }or.overrideProvider(...).useValue(...)- Set an environment variable
- You can't; Nest always uses real providers
Which library do Nest e2e tests use by default to send HTTP requests?
- axios
- supertest
- Playwright
- curl
Why might a ValidationPipe set up in main.ts not run in your e2e tests?
- Pipes never run in tests
- e2e tests build the app from
AppModule, which doesn't include whatmain.tsconfigures - Jest disables validation
- supertest strips request bodies