How to test the type of a thrown exception in Jest

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

    I ended up writing a convenience method for our test-utils library

    /**
     *  Utility method to test for a specific error class and message in Jest
     * @param {fn, expectedErrorClass, expectedErrorMessage }
     * @example   failTest({
          fn: () => {
            return new MyObject({
              param: 'stuff'
            })
          },
          expectedErrorClass: MyError,
          expectedErrorMessage: 'stuff not yet implemented'
        })
     */
      failTest: ({ fn, expectedErrorClass, expectedErrorMessage }) => {
        try {
          fn()
          expect(true).toBeFalsy()
        } catch (err) {
          let isExpectedErr = err instanceof expectedErrorClass
          expect(isExpectedErr).toBeTruthy()
          expect(err.message).toBe(expectedErrorMessage)
        }
      }
    

提交回复
热议问题