Bird
Raised Fist0
NestJSframework~10 mins

Mocking providers in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Mocking providers
Define real provider
↓
Create mock object
↓
Override provider in test module
↓
Inject mock provider in test
↓
Run test with mock behavior
↓
Verify mock calls and results
This flow shows how to replace a real provider with a mock in NestJS tests to control behavior and verify interactions.
Execution Sample
NestJS
const mockUserService = { findAll: jest.fn().mockReturnValue(['user1', 'user2']) };

let userService;

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

  userService = module.get<UserService>(UserService);
});
This code creates a mock for UserService and overrides it in the test module to control its findAll method.
Execution Table
StepActionMock SetupTest Module ProviderInjected ProviderTest Behavior
1Define mockUserServicefindAll mocked to return ['user1', 'user2']N/AN/AN/A
2Create test moduleN/AUserService replaced by mockUserServiceN/AN/A
3Compile test moduleN/AMock provider readyN/AN/A
4Inject UserServiceN/AN/AmockUserService injectedN/A
5Call findAll()N/AN/AmockUserService.findAll() calledReturns ['user1', 'user2']
6Verify callsN/AN/AmockUserService.findAll() call count checkedTest passes if call count is correct
7Test endsN/AN/AN/ATest completes successfully
💡 Test ends after verifying mock provider behavior and call counts
Variable Tracker
VariableStartAfter Step 1After Step 4After Step 5Final
mockUserServiceundefined{ findAll: jest.fn().mockReturnValue(['user1', 'user2']) }{ findAll: jest.fn().mockReturnValue(['user1', 'user2']) }{ findAll: jest.fn().mockReturnValue(['user1', 'user2']) }{ findAll: jest.fn().mockReturnValue(['user1', 'user2']) }
Test Module ProviderUserService realUserService realUserService mockedUserService mockedUserService mocked
Injected ProviderundefinedundefinedmockUserServicemockUserServicemockUserService
findAll() call count00011
Key Moments - 3 Insights
Why do we use useValue instead of useClass when mocking a provider?
useValue lets us provide a custom mock object directly, as shown in execution_table step 2, allowing precise control over methods like findAll.
How does the test know to use the mock instead of the real provider?
Because in the test module setup (step 2), the provider is overridden with the mock using provide and useValue, so injection returns the mock (step 4).
What happens if we forget to mock a method used in the test?
The test will call the real method or fail if undefined; mocking ensures controlled return values as seen in step 5 where findAll returns the mock data.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the injected provider at step 4?
AmockUserService
BReal UserService
CUndefined
DJest mock function
💡 Hint
Check the 'Injected Provider' column at step 4 in the execution_table.
At which step does the findAll method get called?
AStep 2
BStep 3
CStep 5
DStep 6
💡 Hint
Look at the 'Test Behavior' column to find when findAll() is called.
If we did not override the provider in the test module, what would the 'Injected Provider' be at step 4?
AmockUserService
BReal UserService
CUndefined
DJest mock function
💡 Hint
Refer to the 'Test Module Provider' and 'Injected Provider' columns in the execution_table steps 2 and 4.
Concept Snapshot
Mocking providers in NestJS tests:
- Create a mock object with jest.fn() methods
- Override provider in Test.createTestingModule with { provide: RealService, useValue: mock }
- Inject provider in tests to get mock
- Control method returns and verify calls
- Enables isolated, predictable tests
Full Transcript
In NestJS testing, mocking providers means replacing real services with fake ones that behave as we want. First, we define a mock object with jest.fn() methods to simulate real methods. Then, in the test module setup, we override the real provider by specifying useValue with our mock. When the test runs, injecting the provider gives us the mock instead of the real service. We call methods on the mock, which return controlled values, and we can check how many times they were called. This helps us test components in isolation without relying on real implementations.

Practice

(1/5)
1. What is the main purpose of mocking providers in NestJS tests?
easy
A. To replace real services with fake ones to isolate tests
B. To speed up the application in production
C. To add new features to the service
D. To automatically generate database records

Solution

  1. Step 1: Understand the role of mocking in tests

    Mocking replaces real dependencies with controlled fake versions to isolate the code under test.
  2. Step 2: Identify the purpose in NestJS context

    In NestJS, mocking providers helps avoid side effects and external calls during testing.
  3. Final Answer:

    To replace real services with fake ones to isolate tests -> Option A
  4. Quick Check:

    Mocking = isolate tests [OK]
Hint: Mocking means replacing real parts with fakes in tests [OK]
Common Mistakes:
  • Thinking mocking speeds up production
  • Confusing mocking with adding features
  • Assuming mocking generates data automatically
2. Which syntax correctly mocks a provider in a NestJS test module?
easy
A. { provide: RealService, useValue: mockService }
B. { provide: mockService, useClass: RealService }
C. { useValue: RealService, provide: mockService }
D. { useClass: mockService, provide: RealService }

Solution

  1. Step 1: Recall NestJS mocking syntax

    Mocking uses an object with keys 'provide' for the real service and 'useValue' for the mock.
  2. Step 2: Match correct key order and values

    { provide: RealService, useValue: mockService } correctly uses 'provide' with the real service and 'useValue' with the mock object.
  3. Final Answer:

    { provide: RealService, useValue: mockService } -> Option A
  4. Quick Check:

    Mock syntax = provide + useValue [OK]
Hint: Remember: provide real, useValue mock [OK]
Common Mistakes:
  • Swapping provide and useValue keys
  • Using useClass instead of useValue for mocks
  • Putting mock as provide instead of real service
3. Given this NestJS test setup:
const mockUserService = { findUser: () => ({ id: 1, name: 'Test' }) };

const moduleRef = await Test.createTestingModule({
  providers: [
    { provide: UserService, useValue: mockUserService },
  ],
}).compile();

const service = moduleRef.get(UserService);
const user = service.findUser();
console.log(user);
What will be logged to the console?
medium
A. Error: UserService not found
B. undefined
C. { id: 1, name: 'Test' }
D. { findUser: [Function] }

Solution

  1. Step 1: Understand the mock provider setup

    The mockUserService has a method findUser returning an object with id and name.
  2. Step 2: Check what service.findUser() returns

    Since the mock is used, calling findUser() returns { id: 1, name: 'Test' } as defined.
  3. Final Answer:

    { id: 1, name: 'Test' } -> Option C
  4. Quick Check:

    Mock method returns object [OK]
Hint: Mock methods return defined fake data [OK]
Common Mistakes:
  • Expecting real service output instead of mock
  • Assuming service is undefined
  • Confusing method with object itself
4. You wrote this test code but get an error: TypeError: service.findUser is not a function. What is the likely cause?
const mockUserService = {};

const moduleRef = await Test.createTestingModule({
  providers: [
    { provide: UserService, useValue: mockUserService },
  ],
}).compile();

const service = moduleRef.get(UserService);
service.findUser();
medium
A. useClass should be used instead of useValue
B. UserService was not provided in the module
C. The compile() method was not awaited
D. The mockUserService does not define the findUser method

Solution

  1. Step 1: Check the mock object definition

    The mockUserService is an empty object with no findUser method defined.
  2. Step 2: Understand the error cause

    Calling findUser on an object without that method causes TypeError.
  3. Final Answer:

    The mockUserService does not define the findUser method -> Option D
  4. Quick Check:

    Missing method in mock = TypeError [OK]
Hint: Ensure mock defines all called methods [OK]
Common Mistakes:
  • Assuming compile() missing await causes this error
  • Confusing useClass and useValue for mocks
  • Thinking provider missing causes this specific error
5. You want to test a service that depends on another service with a method returning a promise. How do you mock the provider to return a resolved promise with value 'done'?
hard
A. { provide: DepService, useValue: { asyncMethod: () => 'done' } }
B. { provide: DepService, useValue: { asyncMethod: () => Promise.resolve('done') } }
C. { provide: DepService, useValue: { asyncMethod: () => async () => 'done' } }
D. { provide: DepService, useValue: { asyncMethod: () => new Promise('done') } }

Solution

  1. Step 1: Understand mocking async methods

    To mock a method returning a promise resolved with 'done', use Promise.resolve('done').
  2. Step 2: Check each option for correct promise return

    { provide: DepService, useValue: { asyncMethod: () => Promise.resolve('done') } } correctly returns Promise.resolve('done'). { provide: DepService, useValue: { asyncMethod: () => 'done' } } returns a string, not a promise. { provide: DepService, useValue: { asyncMethod: () => async () => 'done' } } returns a function, not a promise. { provide: DepService, useValue: { asyncMethod: () => new Promise('done') } } incorrectly uses new Promise with a string argument.
  3. Final Answer:

    { provide: DepService, useValue: { asyncMethod: () => Promise.resolve('done') } } -> Option B
  4. Quick Check:

    Mock async with Promise.resolve(value) [OK]
Hint: Use Promise.resolve('value') to mock async returns [OK]
Common Mistakes:
  • Returning plain value instead of promise
  • Incorrect new Promise usage
  • Confusing async function syntax with promise return
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard