In NestJS, you can easily mock responses using Jest, a popular testing framework. Jest provides powerful mocking capabilities that allow you to create mock implementations of dependencies, services, and external APIs to test your NestJS application's behavior.
To mock a response in a NestJS controller or service, you can use the jest.fn()
method to create a mock function that returns the desired response. Here's an example of how you can do it:
Let's assume you have a simple NestJS controller that fetches user data from a service:
typescript// user.controller.ts
import { Controller, Get } from '@nestjs/common';
import { UserService } from './user.service';
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get(':id')
async getUser(@Param('id') id: string) {
return this.userService.getUserById(id);
}
}
And here's the UserService
that fetches user data from an external API:
typescript// user.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class UserService {
async getUserById(id: string) {
// Call the external API to fetch user data based on the ID
// For example, let's assume we call an API and get the response
const response = await fetch(`https://example.com/api/users/${id}`);
const userData = await response.json();
return userData;
}
}
To test the UserController
and mock the UserService
response, you can use Jest's mocking capabilities:
typescript// user.controller.spec.ts
import { Test } from '@nestjs/testing';
import { UserController } from './user.controller';
import { UserService } from './user.service';
describe('UserController', () => {
let userController: UserController;
let userService: UserService;
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
controllers: [UserController],
providers: [UserService],
}).compile();
userController = moduleRef.get<UserController>(UserController);
userService = moduleRef.get<UserService>(UserService);
});
describe('getUser', () => {
it('should return user data', async () => {
// Create a mock user data to be returned by the mock service
const mockUserData = { id: '1', name: 'John Doe' };
// Mock the response of the userService.getUserById method
jest.spyOn(userService, 'getUserById').mockResolvedValue(mockUserData);
// Call the getUser method of the controller with a mocked request object
const result = await userController.getUser('1');
// Expect the result to be equal to the mock user data
expect(result).toEqual(mockUserData);
});
});
});
In the test above, we use Jest's jest.spyOn
method to create a mock implementation of the userService.getUserById
method. We then use mockResolvedValue
to set the return value of the mocked method to the mockUserData
object. This way, when the getUser
method of the UserController
is called with an ID, it will use the mocked response from the UserService
.
By mocking the response of the UserService
, you can test the behavior of your controller without relying on the actual external API call, making your tests more predictable and isolated.