Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test throw new HttpException in unit test Nest.js

I'm trying to test a service in my Nest.js app. In some of my methods of this service I have some cases where I throw new HttpException depending of the context.

I'm trying to write unit tests of these methods and I don't know how to test cases where I throw HttpException.

I've tried this code:

it('Shound return error for a non existing id provided', async () => {
      await expect(service.getUser('false Id')).rejects.toThrow(new HttpException('This user does not exist', 404));
});

But I received:

Expected the function to throw an error matching:
      [Error: This user does not exist]
    Instead, it threw:
      Error: This user does not exist

Does anyone already encounter this use case ?

like image 807
user2871045 Avatar asked Feb 07 '20 17:02

user2871045


2 Answers

Simply do this:

  it('should return null when update', async (done) => {
    jest.spyOn(service, 'updateById').mockResolvedValue(null)

    try {
      await controller.updateById({ id: 'some id' }, {})
    } catch (error) {
      expect(error).toBeInstanceOf(NotFoundException)
      done()
    }
  })
like image 69
Duc Trung Mai Avatar answered Sep 22 '22 01:09

Duc Trung Mai


Duc answer works but if you want some prettier way you might like this,

 it('should return null when update', async () => {

  await expect(controller.updateById({ id: 'some id' }, {}))
  .rejects.toThrowError(NotFoundException);

});
like image 32
M.abdelrhman Avatar answered Sep 22 '22 01:09

M.abdelrhman