Mocking providers helps you test parts of your NestJS app without using real services. It makes tests faster and safer.
0
0
Mocking providers in NestJS
Introduction
When you want to test a controller without calling the real service.
When a service depends on a database, and you want to avoid real database calls during tests.
When you want to simulate different responses from a service to test error handling.
When you want to isolate a unit of code to check its behavior alone.
Syntax
NestJS
const mockProvider = {
provide: ServiceToMock,
useValue: {
methodName: jest.fn().mockReturnValue(mockValue),
},
};provide is the token or class you want to mock.
useValue is the fake object with mocked methods.
Examples
This mocks
UserService with a fake findUser method returning a test user.NestJS
const mockUserService = {
provide: UserService,
useValue: {
findUser: jest.fn().mockReturnValue({ id: 1, name: 'Test' }),
},
};This mocks
LoggerService with a log method that does nothing but can track calls.NestJS
const mockLogger = {
provide: LoggerService,
useValue: {
log: jest.fn(),
},
};Sample Program
This test mocks UsersService inside the test module. The UsersController uses the mock instead of the real service. The test checks that findAll returns the mocked user list and that the service method was called.
NestJS
import { Test } from '@nestjs/testing'; import { UsersController } from './users.controller'; import { UsersService } from './users.service'; describe('UsersController', () => { let usersController: UsersController; let usersService: UsersService; const mockUsersService = { findAll: jest.fn().mockReturnValue([{ id: 1, name: 'Alice' }]), }; beforeEach(async () => { const moduleRef = await Test.createTestingModule({ controllers: [UsersController], providers: [ { provide: UsersService, useValue: mockUsersService, }, ], }).compile(); usersController = moduleRef.get<UsersController>(UsersController); usersService = moduleRef.get<UsersService>(UsersService); }); it('should return an array of users', () => { expect(usersController.findAll()).toEqual([{ id: 1, name: 'Alice' }]); expect(usersService.findAll).toHaveBeenCalled(); }); });
OutputSuccess
Important Notes
Use jest.fn() to create mock functions that can track calls and return values.
Mocking helps keep tests fast and independent from external systems.
Remember to reset mocks between tests if needed to avoid test interference.
Summary
Mocking providers replaces real services with fake ones in tests.
This helps isolate the code you want to test and avoid side effects.
Use provide and useValue to define mocks in NestJS test modules.