Given a NestJS service mocked to always return 42 for a method call, what will the controller return when calling that method?
class RealService { getValue() { return Math.random(); } } const mockService = { getValue: () => 42 }; class Controller { constructor(private service) {} fetch() { return this.service.getValue(); } } const controller = new Controller(mockService); console.log(controller.fetch());
Think about what the mocked method returns instead of the real one.
The mocked service's getValue method always returns 42. So the controller's fetch method returns 42 as well.
Which code snippet correctly mocks a provider named DataService in a NestJS testing module?
import { Test } from '@nestjs/testing'; import { DataService } from './data.service'; const mockDataService = { fetch: () => 'mocked data' }; async function setup() { const moduleRef = await Test.createTestingModule({ providers: [ DataService, // Mock provider here ], }).compile(); return moduleRef; }
Remember the syntax for replacing a provider with a mock object.
To mock a provider, use provide with the original class and useValue with the mock object. Option D follows this pattern correctly.
In this NestJS test setup, the mock provider does override the real service. What is the cause?
const moduleRef = await Test.createTestingModule({
providers: [
RealService,
{ provide: RealService, useValue: mockService },
],
}).compile();Consider how NestJS handles multiple providers with the same token.
NestJS uses the last provider with the same token when resolving dependencies. So the mock provider correctly overrides the real one.
Given a mocked provider method that tracks call count, what is the value of callCount after three calls?
const mockService = {
callCount: 0,
fetch() {
this.callCount++;
return 'data';
}
};
mockService.fetch();
mockService.fetch();
mockService.fetch();
console.log(mockService.callCount);Think about how the method updates the callCount property.
Each call to fetch increments callCount by 1. After three calls, it becomes 3.
Why do developers mock providers in NestJS unit tests?
Think about the goal of unit testing and how mocks help.
Mocking providers isolates the unit under test by replacing real dependencies with controlled mocks, ensuring tests are focused and predictable.