I've a simple controller in my NestJs application.
@Post('/')
async create(@Body() createUserRequest: CreateUserRequest): Promise<User> {
return await this.userService.create(createUserRequest);
}
My goal is to test this function using jest. As you can see the controller injects an instance of UserService. So I try to mock this service in my unit test. The test case looks like this.
describe('User Controller', () => {
let userService: UserService;
let userController: UserController;
beforeEach(async () => {
const module = await Test.createTestingModule({
controllers: [UserController],
providers: [UserService],
}).compile();
userService = module.get<UserService>(UserService);
userController = module.get<UserController>(UserController);
});
describe('create', () => {
it('should return a user', async () => {
const result = new User();
jest.spyOn(userService, 'create').mockImplementation(() => result);
expect(await userController.create(new CreateUserRequest())).toBe(result);
});
});
});
My problem is that jest.spyOn where the mocking happens produces an error.
No overload matches this call.
Overload 1 of 4, '(object: UserService, method: never): SpyInstance<never, never>', gave the following error.
Argument of type '"create"' is not assignable to parameter of type 'never'.
Overload 2 of 4, '(object: UserService, method: never): SpyInstance<never, never>', gave the following error.
Argument of type '"create"' is not assignable to parameter of type 'never'.
Has anyone an idea what is wrong with my mock? I took this approach from the documentation.