0
0
NestjsHow-ToBeginner ยท 4 min read

How to Mock Service in NestJS Test: Simple Guide

To mock a service in a nestjs test, use jest.fn() to create mock functions and provide them in the TestingModule with useValue. This lets you replace the real service with a mock version for isolated testing.
๐Ÿ“

Syntax

In NestJS tests, you create a mock service object with Jest mock functions and provide it to the testing module using useValue. This replaces the real service with your mock.

  • jest.fn(): Creates a mock function.
  • useValue: Supplies the mock object instead of the real service.
  • TestingModule: NestJS test module to configure providers.
typescript
const mockService = {
  methodName: jest.fn(),
};

const moduleRef = await Test.createTestingModule({
  providers: [
    { provide: DependencyService, useValue: mockService },
  ],
}).compile();
๐Ÿ’ป

Example

This example shows how to mock a UserService inside a test for UserController. The mock replaces UserService methods with Jest mock functions to control their behavior.

typescript
import { Test, TestingModule } from '@nestjs/testing';
import { UserController } from './user.controller';
import { UserService } from './user.service';

describe('UserController', () => {
  let userController: UserController;
  let userService: UserService;

  const mockUserService = {
    findAll: jest.fn().mockResolvedValue([{ id: 1, name: 'Alice' }]),
    findOne: jest.fn().mockImplementation((id: number) => Promise.resolve({ id, name: 'Alice' })),
  };

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UserController],
      providers: [
        { provide: UserService, useValue: mockUserService },
      ],
    }).compile();

    userController = module.get<UserController>(UserController);
    userService = module.get<UserService>(UserService);
  });

  it('should return an array of users', async () => {
    const users = await userController.findAll();
    expect(users).toEqual([{ id: 1, name: 'Alice' }]);
    expect(userService.findAll).toHaveBeenCalled();
  });

  it('should return a single user by id', async () => {
    const user = await userController.findOne(1);
    expect(user).toEqual({ id: 1, name: 'Alice' });
    expect(userService.findOne).toHaveBeenCalledWith(1);
  });
});
Output
PASS UserController โœ“ should return an array of users (5 ms) โœ“ should return a single user by id (2 ms)
โš ๏ธ

Common Pitfalls

Common mistakes when mocking services in NestJS tests include:

  • Not providing the mock with useValue, causing the real service to be used.
  • Forgetting to mock all methods used by the tested component, leading to undefined is not a function errors.
  • Not resetting mocks between tests, causing unexpected test interference.

Always ensure your mock object matches the service interface and reset mocks with jest.clearAllMocks() in beforeEach.

typescript
beforeEach(() => {
  jest.clearAllMocks();
});
๐Ÿ“Š

Quick Reference

Tips for mocking services in NestJS tests:

  • Use jest.fn() to create mock functions.
  • Provide mocks with useValue in TestingModule.
  • Mock all service methods your test calls.
  • Reset mocks between tests with jest.clearAllMocks().
  • Use mockResolvedValue for async methods returning promises.
โœ…

Key Takeaways

Mock services in NestJS tests by providing a mock object with jest.fn() using useValue in TestingModule.
Always mock all methods your test depends on to avoid runtime errors.
Reset mocks between tests with jest.clearAllMocks() to keep tests independent.
Use mockResolvedValue for async service methods to simulate promises.
Providing mocks isolates your tests from real dependencies for reliable unit testing.