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?
Compared to examples in jest documentation, you may have 2 problems here.
await
should be outside the expect
argumentrejects
implies an error was thrown, so you test for equalitySomething like:
it('test', async () => {
await expect(userController.doSomething())
.rejects.toEqual(new BadRequestException({ data: '', error: 'foo'});
});
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