Test One Provider in Isolation
Unit Testing With Jest
Nest's Test.createTestingModule builds a TS test container where you can override any provider with a mock.
What you'll learn
- Use Test.createTestingModule and compile()
- Override providers with useValue or useFactory mocks
- Assert on the unit under test with Jest
Nest ships a tiny testing helper that builds a real DI container with the providers you list — no Nest application, no HTTP server. That makes unit tests fast and isolated.
The Pattern
import { Test } from '@nestjs/testing';
import { UsersService } from './users.service';
import { UsersRepository } from './users.repository';
describe('UsersService', () => {
let service: UsersService;
let repo: jest.Mocked<UsersRepository>;
beforeEach(async () => {
repo = { findAll: jest.fn(), findOne: jest.fn() } as any;
const module = await Test.createTestingModule({
providers: [
UsersService,
{ provide: UsersRepository, useValue: repo },
],
}).compile();
service = module.get(UsersService);
});
it('returns all users', async () => {
repo.findAll.mockResolvedValue([{ id: 1, name: 'Ada' }]);
await expect(service.findAll()).resolves.toHaveLength(1);
expect(repo.findAll).toHaveBeenCalledTimes(1);
});
}); useValue is the simplest mock — a plain object. Use useFactory if the
mock needs to depend on other test fixtures.
Why Not New The Class Directly?
You could write new UsersService(repo) and skip Nest entirely — and for
truly trivial classes that is fine. The moment a class injects more than
one dep, the testing module saves you from re-typing constructor
signatures on every test.
Auto-Mocking Big Dependencies
For services with many collaborators, define a factory:
const mockRepo = () => ({
findAll: jest.fn(),
findOne: jest.fn(),
save: jest.fn(),
});
const module = await Test.createTestingModule({
providers: [
UsersService,
{ provide: UsersRepository, useFactory: mockRepo },
],
}).compile(); What To Cover
- Branching logic inside services.
- Edge cases in pipes and guards.
- Custom decorators and reflection helpers.
Skip unit tests for thin controllers — e2e tests cover them better.
End-to-End Testing →