Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *