I have this particular error: "TypeError: this.commentRepository.save is not a function"
When I run this simple test:
describe('CommentService', () => {
let commentService: CommentService;
const mockCommentRepository = {
createComment: jest.fn(comment => comment),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
CommentService,
{
provide: getRepositoryToken(Comment),
useValue: mockCommentRepository,
}
],
}).compile();
commentService = module.get<CommentService>(CommentService);
});
it('should create a comment', async () => {
expect(await commentService.createComment({ message: 'test message'})).toEqual({
id: expect.any(Number),
message: 'test message',
});
});
});
The service:
async createComment(comment: Partial<Comment>): Promise<Comment> {
return await this.commentRepository.save(comment);
}
Can someone help me ?
CodePudding user response:
Your mockCommentRepository
does not have save()
method you are calling in your service createComment
method. Mock this method as well to get rid of the error.
Also refer to this answer for more info on repository mocking https://stackoverflow.com/a/55366343/5716745
CodePudding user response:
Since you are trying to create a provider for the Repository you have to mock the repository methods (in this case the save function).
{
provide: getRepositoryToken(Comment),
useValue: {
save: jest.fn().mockResolvedValue(null),
},
},