Use “toThrowError” and “toThrow” in TypeScript with Objects

Posted by in Software

TL;DR: wrap your method call in the expect() statement. Instead of expect(obj.method()).toThrow(), write expect( () => { obj.method() }).toThrow().

While in the process of improving the code coverage, I needed to write a test for a method throwing an exception. My initial code would have been something like:

Where SelectorComponent has a method named updateSelectors(value: any) which throws an error if the value is not in an array.

If I write the test as above, it will fail (the test itself will throw the error):

However, If I write the test as:

The test will complete nicely with the error being caught and processed by the test suite.

Same approach is valid for toThrowError() :)


A little experiment: If you find this post and ad below useful, please check the ad out :-)