用Jest测试类型异常

时间:2019-03-06 03:37:20

标签: javascript typescript unit-testing jestjs

Attempting to utilize the approach outlined in this SO post

我有以下类型的异常:

    /**
     * @param message The error message
     * @param value The value that violates the constraint
     * @param field The name of the field
     * @param type The expected type for the field
     * @param code The application or module code for the error
     */
    export class IsError extends Error {
      constructor(
        public message:string,
        public value: any, 
        public field:string, 
        public type: string,
        public code?:string) {
          super(message);
          this.name = 'IsError';
      }
    }

此函数将其抛出:

 export function isBooleanError(value: any, field:string, code?: string): void {
      if (!isBoolean(value)) {
        const message:string = `The field ${field} should be a boolean valued.  It is set to ${value}. `;
        throw new IsError(message, value, field, BOOLEAN_TYPE, code);
      }
    }

这有效:

expect(()=>{isBooleanError({}, '')}).toThrow(Error);

但这不是:

expect(()=>{isBooleanError({}, '')}).toThrow(IsError);

谁知道后者为什么不起作用?开玩笑的日志:

expect(received).toThrow(expected)

Expected name: "IsError"
Received name: "Error"

1 个答案:

答案 0 :(得分:0)

我必须将此添加到异常的构造函数中:

  super(message);
  Object.setPrototypeOf(this, IsError.prototype);