How to test the type of a thrown exception in Jest

后端 未结 12 1211
误落风尘
误落风尘 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条回答
  • I use a slightly more concise version:

    expect(() => {
      // Code block that should throw error
    }).toThrow(TypeError) // Or .toThrow('expectedErrorMessage')
    
    0 讨论(0)
  • 2020-12-04 19:18

    The documentation is clear on how to do this. Let's say I have a function that takes two parameters and it will throw an error if one of them is null.

    function concatStr(str1, str2) {
      const isStr1 = str1 === null
      const isStr2 = str2 === null
      if(isStr1 || isStr2) {
        throw "Parameters can't be null"
      }
      ... // Continue your code
    

    Your test

    describe("errors", () => {
      it("should error if any is null", () => {
        // Notice that the expect has a function that returns the function under test
        expect(() => concatStr(null, "test")).toThrow()
      })
    })
    
    0 讨论(0)
  • 2020-12-04 19:19

    Try:

    expect(t).rejects.toThrow()
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-04 19:24

    In case you are working with Promises:

    await expect(Promise.reject(new HttpException('Error message', 402)))
      .rejects.toThrowError(HttpException);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题