Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expecting specific error when writing unit tests in jest

I use nestjs (6.5.0) and jest (24.8) and have a method that throws an error:

  public async doSomething(): Promise<{ data: string, error?: string }> {
    throw new BadRequestException({ data: '', error: 'foo' });
  }

How can I write a unit test that checks that we get the expected exception with the expected data? The obvious solution is:

it('test', async () => {
  expect(await userController.doSomething())
    .rejects.toThrowError(new BadRequestException({ data: '', error: 'foo'});
});

but that doesn't work because new BadRequestException() creates an object with a different call stack. How can I test this?

like image 418
decocijo Avatar asked Jan 27 '23 07:01

decocijo


1 Answers

Compared to examples in jest documentation, you may have 2 problems here.

  • await should be outside the expect argument
  • rejects implies an error was thrown, so you test for equality

Something like:

it('test', async () => {
  await expect(userController.doSomething())
    .rejects.toEqual(new BadRequestException({ data: '', error: 'foo'});
});
like image 199
Sergio Mazzoleni Avatar answered Jan 31 '23 18:01

Sergio Mazzoleni