tommyd456
tommyd456

Reputation: 10673

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?

Upvotes: 15

Views: 59324

Answers (2)

Aday Mesa
Aday Mesa

Reputation: 1

You can wrap the expectation inside setImmediate() or process.nextTick() as:

test('the fetch fails with an error', async => {
  expect.assertions(1);
  setImmediate(() => {
   expect(fetchData).toMatch('error');
  });
});

Upvotes: 0

jahller
jahller

Reputation: 2963

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');
  }
});

Upvotes: 21

Related Questions