How to test the type of a thrown exception in Jest

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

    Modern Jest allows you to make more checks on a rejected value. For example:

    const request = Promise.reject({statusCode: 404})
    await expect(request).rejects.toMatchObject({ statusCode: 500 });
    

    will fail with error

    Error: expect(received).rejects.toMatchObject(expected)
    
    - Expected
    + Received
    
      Object {
    -   "statusCode": 500,
    +   "statusCode": 404,
      }
    

提交回复
热议问题