When writing tests for your JavaScript code, it’s essential to verify that functions behave as expected when encountering errors. Jest provides several ways to test for thrown exceptions, allowing you to ensure your code handles errors correctly. In this tutorial, we’ll explore how to use Jest to test for thrown exceptions, including testing the type and message of the error.
Using expect().toThrow()
The most straightforward way to test for a thrown exception in Jest is by using the expect().toThrow()
method. This method takes an optional argument, which can be either the expected error type or the expected error message.
test('throws TypeError', () => {
const t = () => {
throw new TypeError();
};
expect(t).toThrow(TypeError);
});
You can also test for a specific error message:
test('throws TypeError with message', () => {
const t = () => {
throw new TypeError('UNKNOWN ERROR');
};
expect(t).toThrow('UNKNOWN ERROR');
});
Testing Existing Functions
If you need to test an existing function that throws an exception, you can wrap it inside an anonymous function in expect()
:
test('throws TypeError', () => {
expect(() => {
// Code block that should throw error
}).toThrow(TypeError);
});
Using Try-Catch Blocks
Another approach is to use a try-catch block to catch the thrown exception and then verify its type and message using expect()
:
test('throws TypeError with message', () => {
expect.assertions(2);
try {
// Code block that should throw error
throwError();
} catch (error) {
expect(error).toBeInstanceOf(TypeError);
expect(error.message).toBe('UNKNOWN ERROR');
}
});
In this example, expect.assertions(2)
ensures that the test fails if no exception is thrown.
Testing Async Code
When testing async code, you can use await expect()
with .rejects.toThrow()
to verify that a promise rejects with a specific error:
it('should throw', async () => {
await expect(service.methodName('[email protected]', 'unknown')).rejects.toThrow(
HttpException,
);
});
Best Practices
- Always use
expect.assertions()
when using try-catch blocks to ensure that the test fails if no exception is thrown. - Be specific when testing for error types and messages to avoid false positives.
- Use
toThrow()
with a type or message argument to make your tests more robust.
By following these guidelines and examples, you can effectively test for thrown exceptions in Jest and ensure your code handles errors correctly.