August 2017
Beginner
374 pages
10h 41m
English
It is not enough to test successful cases; sometimes you also need to test certain failing cases (for example, invalid username handled properly).
When you want to test if a function throws an error when it is called, you can use the toThrow matcher; for example:
function failingTest () { throw new Error('this is supposed to fail!')}test('failing test', () => { expect(failingTest).toThrow()})
You can also match on the error type, which is useful if you have defined custom errors. For example, to only match an APIError:
expect(failingTest).toThrow(APIError)
Or, you can match on the error message; for example:
expect(failingTest).toThrow(/supposed to fail/)
Read now
Unlock full access