How to test the type of a thrown exception in Jest

后端 未结 12 1229
误落风尘
误落风尘 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:23

    It is a little bit weird, but it works and IMHO is good readable:

    it('should throw Error with message \'UNKNOWN ERROR\' when no parameters were passed', () => {
      try {
          throwError();
          // Fail test if above expression doesn't throw anything.
          expect(true).toBe(false);
      } catch (e) {
          expect(e.message).toBe("UNKNOWN ERROR");
      }
    });
    

    The Catch block catches your exception, and then you can test on your raised Error. Strange expect(true).toBe(false); is needed to fail your test if the expected Error will be not thrown. Otherwise, this line is never reachable (Error should be raised before them).

    @Kenny Body suggested a better solution which improve a code quality if you use expect.assertions():

    it('should throw Error with message \'UNKNOWN ERROR\' when no parameters were passed', () => {
      expect.assertions(1);
      try {
          throwError();
      } catch (e) {
          expect(e.message).toBe("UNKNOWN ERROR");
      }
    });
    

    See the original answer with more explanations: How to test the type of a thrown exception in Jest

提交回复
热议问题