Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - testing try/catch

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?

like image 879
tommyd456 Avatar asked Jun 01 '18 12:06

tommyd456


People also ask

How to fix jest test with timeout error?

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 to use the try- catch idiom in a test code?

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.

How do you handle asynchronous tests in jest?

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.

What is jest testing and why should you use it?

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.


Video Answer


1 Answers

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');
  }
});
like image 75
jahller Avatar answered Oct 07 '22 01:10

jahller