etrix
etrix

Reputation: 79

NestJS service testing: try to test a simple save

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?

Upvotes: 2

Views: 105

Answers (2)

3ximus
3ximus

Reputation: 400

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

Upvotes: 1

Dezzley
Dezzley

Reputation: 1835

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

Upvotes: 2

Related Questions