How to test the type of a thrown exception in Jest

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

    I haven't tried it myself, but I would suggest using Jest's toThrow assertion. So I guess your example would look something like this:

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

    Again, I haven't test it, but I think it should work.

提交回复
热议问题