【问题标题】:Testing for typed exceptions with Jest使用 Jest 测试类型异常
【发布时间】:2019-07-27 15:33:06
【问题描述】:

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"

【问题讨论】:

    标签: javascript typescript unit-testing jestjs


    【解决方案1】:

    我不得不将这个添加到异常的构造函数中:

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

    【讨论】:

    • 你需要这个来使instanceofError的子类一起工作:见#13965
    • 好点...有没有一些最终的建议。我通读了链接,但似乎有点悬而未决。能够使用instanceof 会很高兴。 Jest 能够检查抛出的异常是IsError。你知道它使用什么类型的支票吗?
    • 在此处提出后续问题:stackoverflow.com/questions/55065742/…
    猜你喜欢
    • 2018-02-13
    • 1970-01-01
    • 2020-12-19
    • 2020-06-22
    • 1970-01-01
    • 2023-01-19
    • 2018-09-11
    • 2012-04-25
    相关资源
    最近更新 更多