How to test the type of a thrown exception in Jest

后端 未结 12 1230
误落风尘
误落风尘 2020-12-04 18:37

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

12条回答
  •  感动是毒
    2020-12-04 19:05

    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);
    });
    

    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);
    });
    

提交回复
热议问题