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 ?
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()
}
})
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With