I am trying to test this class method:
get () {
try {
return 'value'
} catch (e) {
return 'value2'
}
}
with:
test('the get method retrieves value', () => {
const value = MyClass.get()
expect(value).toBe('value')
})
My test coverage shows I have tested the try
part of the method but not the catch
part.
How can I cover the catch
part?
There is an alternate form of test that fixes this. Instead of putting the test in a function with an empty argument, use a single argument called done. Jest will wait until the done callback is called before finishing the test. If done () is never called, the test will fail (with timeout error), which is what you want to happen.
When testing the code that throws exceptions, one immediately comes up with the idea of using the try-catch idiom in the test code: Generally speaking, this is not the best approach. The test passes when the first argument is null as expected. But when the code is about to change and the exception won’t be thrown anymore the test still passes.
If your code uses promises, there is a more straightforward way to handle asynchronous tests. Return a promise from your test, and Jest will wait for that promise to resolve. If the promise is rejected, the test will automatically fail.
The JavaScript testing framework Jest offers many, many ways to handle tests just like this, and if we take the time to write them it may end up saving us a brutal, stressful debugging session sometime down the road when something’s gone wrong in production and its imperative to identify the problem and fix it.
You can test the catch part by wrapping the function call in a try catch
block in your test AND expecting an assertion. Without expecting an assertion a run of the test that doesn't cause an error will still pass.
https://jestjs.io/docs/en/tutorial-async#error-handling
test('the fetch fails with an error', async done => {
expect.assertions(1);
try {
await fetchData();
} catch (e) {
expect(e).toMatch('error');
}
});
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