0
0
NestJSframework~10 mins

Mocking providers in NestJS - Step-by-Step Execution

Choose your learning style9 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.