玩笑例外同时匹配类型和消息

时间:2019-03-25 19:27:31

标签: javascript jestjs

我想编写一个测试,该异常的类型和消息都很重要。

function foo(){
    throw new CustomError("foobar");
}

有没有比两次调用函数更好的测试方法了?

test("should throw a CustomError with the right message", () => {
    expect(() => foo()).toThrow(CustomError);
    expect(() => foo()).toThrow("foobar");
});

2 个答案:

答案 0 :(得分:1)

您要的功能在Jest GitHub issue #3659中被请求并被拒绝。但是,它已作为toThrowWithMessage()添加到了单独的扩展了笑话的项目中。太好了!

您的示例代码如下:

test("should throw a CustomError with the right message", () => {
    expect(() => foo()).toThrowWithMessage(CustomError, "foobar");
});

有关更多信息,请参见the documentation。请注意,除了简单地安装jest-extended以外,还需要一些配置才能使用它们的匹配器。有关详细信息,请参见the setup section of their documentation

如果您不想使用jest-extended,那么只要the license被您接受,就可以始终将其匹配器复制到您的代码库中。否则,我认为您提供的示例是检查错误类和消息的好方法。

答案 1 :(得分:0)

如果您想要这个确切的错误,请考虑使用以下内容:

test("should throw a CustomError with the right message", () => {
    expect(() => foo()).toThrow(new CustomError("foobar");
});

here

所述