How to test the type of a thrown exception in Jest?

Sometimes, we want to test the type of a thrown exception in Jest.

In this article, we’ll look at how to test the type of a thrown exception in Jest.

How to test the type of a thrown exception in Jest?

To test the type of a thrown exception in Jest, we can use the thThrow method.

For instance, we write:

test("a test", () => {
  const t = () => {
    throw new TypeError();
  };
  expect(t).toThrow(TypeError);
});

to throw a TypeError in t.

Then we check that t throws a TypeError when we call it with expect(t).toThrow(TypeError);.

Conclusion

To test the type of a thrown exception in Jest, we can use the thThrow method.