Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test an exception was not thrown with Jest?

The Jest docs do not demonstrate a way of asserting that no exception was thrown, only that one was.

expect(() => ...error...).toThrow(error)

How do I assert if one was not thrown?

like image 514
user9993 Avatar asked Apr 01 '18 22:04

user9993


People also ask

How do you test if an exception is not thrown?

If you want to test a scenario in which an exception should be thrown then you should use the expected annotation. If you want to test a scenario where your code fails and you want to see if the error is correctly handled: use expected and perhaps use asserts to determine if it's been resolved.

How do you throw error in Jest?

to use throw to thrown an error in the mocked implementation of yourMockInstance . If we're mocking async functions, we can use mockRejectedValue to mock the value of a rejected promise returned by the async function. test('async test', async () => { const yourMockFn = jest. fn().

How does Jest test work?

Jest uses a custom resolver for imports in your tests, making it simple to mock any object outside of your test's scope. You can use mocked imports with the rich Mock Functions API to spy on function calls with readable test syntax.


Video Answer


1 Answers

You can always use the .not method, which will be valid if your initial condition is false. It works for every jest test:

expect(() => ...error...).not.toThrow(error) 

https://facebook.github.io/jest/docs/en/expect.html#not

like image 188
Axnyff Avatar answered Sep 30 '22 20:09

Axnyff