Search code examples
javascriptunit-testingjestjs

How to test the type of a thrown exception in Jest


I'm working with some code where I need to test the type of an exception thrown by a function (is it TypeError, ReferenceError, etc.?).

My current testing framework is AVA and I can test it as a second argument t.throws method, like here:

it('should throw Error with message \'UNKNOWN ERROR\' when no params were passed', (t) => {
  const error = t.throws(() => {
    throwError();
  }, TypeError);

  t.is(error.message, 'UNKNOWN ERROR');
});

I started rewriting my tests in Jest and couldn't find how to easily do that. Is it even possible?


Solution

  • In Jest you have to pass a function into expect(function).toThrow(<blank or type of error>).

    Example:

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

    Or if you also want to check for error message:

    test("Test description", () => {
      const t = () => {
        throw new TypeError("UNKNOWN ERROR");
      };
      expect(t).toThrow(TypeError);
      expect(t).toThrow("UNKNOWN ERROR");
    });
    

    If you need to test an existing function whether it throws with a set of arguments, you have to wrap it inside an anonymous function in expect().

    Example:

    test("Test description", () => {
      expect(() => {http.get(yourUrl, yourCallbackFn)}).toThrow(TypeError);
    });