2

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?

Dezzley
  • 1,463
  • 1
  • 13
  • 19
etrix
  • 59
  • 6

2 Answers2

2

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

Dezzley
  • 1,463
  • 1
  • 13
  • 19
  • 2
    const mockCommentRepository = { createComment: jest.fn(comment => comment), save: jest.fn((comment) => comment), }; – etrix Aug 22 '22 at 12:07
0

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),
  },
},