
Running unit tests against a live production database is an anti-pattern that leads to data corruption, slow pipelines, and unreliable test states. Instead, the gold standard is to test your backend services in complete isolation.
Because NestJS is built entirely around Dependency Injection (DI), we can easily intercept its architecture and swap out heavy database connections for lightweight, lightning-fast “mocks.”
In this tutorial, we will break down exactly how to mock TypeORM repositories inside a NestJS unit test using Jest.
The Complete Test Blueprint
Here is the complete unit test file for a standard UsersService. We are going to dissect this file block by block to see how it intercepts NestJS and fakes TypeORM seamlessly.
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UsersService } from './users.service';
import { User } from './user.entity';
import { NotFoundException } from '@nestjs/common';
// 1. Define the mock repository blueprint
type MockRepository<T = any> = Partial<Record<keyof Repository<T>, jest.Mock>>;
const createMockRepository = <T = any>(): MockRepository<T> => ({
findOne: jest.fn(),
save: jest.fn(),
});
describe('UsersService', () => {
let service: UsersService;
let userRepository: MockRepository<User>;
beforeEach(async () => {
// 2. Hijack the NestJS Dependency Injection System
const module: TestingModule = await Test.createTestingModule({
providers: [
UsersService,
{
provide: getRepositoryToken(User),
useValue: createMockRepository(),
},
],
}).compile();
// 3. Extract instances from the test bed
service = module.get<UsersService>(UsersService);
userRepository = module.get<MockRepository<User>>(getRepositoryToken(User));
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('findOne', () => {
// 4. Test Case 1: The "Happy Path" (User Found)
it('should return a user if found', async () => {
const mockUser = { id: 1, name: 'Alice', email: 'alice@example.com' };
userRepository.findOne.mockResolvedValue(mockUser);
const result = await service.findOne(1);
expect(result).toEqual(mockUser);
expect(userRepository.findOne).toHaveBeenCalledWith({ where: { id: 1 } });
});
// 5. Test Case 2: The "Sad Path" (User Not Found)
it('should throw a NotFoundException if user is not found', async () => {
userRepository.findOne.mockResolvedValue(null);
await expect(service.findOne(1)).rejects.toThrow(NotFoundException);
});
});
});
Detailed Walkthrough
1. Creating the Fake Database Blueprint
TypeORM’s real Repository class contains dozens of methods (find, update, delete, etc.). We don’t want to manually mock all of them.
type MockRepository<T = any> = Partial<Record<keyof Repository<T>, jest.Mock>>;
const createMockRepository = <T = any>(): MockRepository<T> => ({
findOne: jest.fn(),
save: jest.fn(),
});
-
The Type Definition: This uses TypeScript utility types (
PartialandRecord) to dynamically scan TypeORM’s real repository. It tells TypeScript: “Create an object where any method from TypeORM is optional, but if I use it, turn it into a Jest spy (jest.Mock).” This keeps things type-safe and gives you full autocomplete without manual boilerplate. -
createMockRepository: This helper factory function returns a clean mock object for our tests. It maps the common database methods tojest.fn(), which are blank tracking spies that we can program to return custom values on the fly.
2. Hijacking NestJS Dependency Injection (beforeEach)
Before every single test case runs, we need to spin up a mini, isolated version of the NestJS runtime environment and intercept the database connection.
const module: TestingModule = await Test.createTestingModule({
providers: [
UsersService,
{
provide: getRepositoryToken(User),
useValue: createMockRepository(),
},
],
}).compile();
-
Test.createTestingModule: This builds a sandbox environment mimicking a real NestJS app module. -
getRepositoryToken(User): In a real app, NestJS uses a hidden internal token to identify repositories injected via@InjectRepository(User). This function gets that exact token. -
useValue: This tells NestJS: “WheneverUsersServiceasks for the real database repository using that token, do not load TypeORM. Inject our fakecreateMockRepository()object instead.”
3. Pulling Instances Out of the Test Bed
Once our sandbox module compiles, we need to grab the instantiated objects so we can manipulate them inside individual tests.
service = module.get<UsersService>(UsersService);
userRepository = module.get<MockRepository<User>>(getRepositoryToken(User));
We extract both the UsersService (which now holds our fake database under the hood) and the raw userRepository mock wrapper so we can tell it how to behave.
4. Test Case 1: The “Happy Path” (User Found)
Now we can safely test how our service handles a successful database retrieval.
it('should return a user if found', async () => {
const mockUser = { id: 1, name: 'Alice', email: 'alice@example.com' };
// 1. Tell the mock what to return
userRepository.findOne.mockResolvedValue(mockUser);
// 2. Execute the actual service code
const result = await service.findOne(1);
// 3. Assertions
expect(result).toEqual(mockUser);
expect(userRepository.findOne).toHaveBeenCalledWith({ where: { id: 1 } });
});
-
mockResolvedValue(mockUser): We explicitly command our mock repository: “The next time the service runsfindOne, simulate a successful database promise resolution with this fake Alice JSON object.” -
The Assertions: We verify that the service processes that database data properly and returns it intact. We also use
toHaveBeenCalledWithto ensure our service actually passed the correct SQL parameters ({ where: { id: 1 } }) to the database driver.
5. Test Case 2: The “Sad Path” (User Not Found)
Good unit tests always check what happens when things go wrong. Here, we ensure our app correctly errors out if a user doesn’t exist.
it('should throw a NotFoundException if user is not found', async () => {
// 1. Tell the mock to pretend the database returned nothing
userRepository.findOne.mockResolvedValue(null);
// 2. Assert that the service crashes with the correct NestJS HTTP exception
await expect(service.findOne(1)).rejects.toThrow(NotFoundException);
});
-
mockResolvedValue(null): We simulate a database query that returns empty-handed. -
rejects.toThrow(NotFoundException): This proves that yourUsersServicecustom error handling handlesnullcorrectly. If the database returns nothing, it interrupts the flow and throws NestJS’s built-inNotFoundException, which automatically translates to a clean404 Not FoundHTTP status code on your frontend application.
Conclusion
By isolating your service layer from the actual database driver using this pattern, your unit tests will execute in milliseconds. They become entirely predictable, completely safe, and run perfectly across local development machines and automated CI/CD pipelines without requiring any database access strings or network connections.
Coding Quote of the Day:
“If it’s worth building, it’s worth testing. If it’s not worth testing, why are you wasting your time building it?” — Scott Ambler
Useful links below:
Let me & my team build you a money making website/blog for your business https://bit.ly/tnrwebsite_service
Get Bluehost hosting for as little as $1.99/month (save 75%)…https://bit.ly/3C1fZd2
Best email marketing automation solution on the market! http://www.aweber.com/?373860
Build high converting sales funnels with a few simple clicks of your mouse! https://bit.ly/484YV29
Join my Patreon for one-on-one coaching and help with your coding…https://www.patreon.com/c/TyronneRatcliff
Buy me a coffee https://buymeacoffee.com/tyronneratcliff



