【问题标题】:Jest: test that exception will be thrown isnt working开玩笑:测试是否会抛出异常不工作
【发布时间】:2020-06-04 07:46:45
【问题描述】:

这个微不足道的类只是一个例子......

class SomeClass{
    getTemplateName() {
        throw new Error('foo');
    }
}

...尝试测试某些代码是否抛出异常

describe('dome class', () => {
    test('contains a method that will throw an exception', () => {
        var sc = new SomeClass();
        expect(sc.getTemplateName()).toThrow(new Error('foo'));
    });
});

但不工作。我做错了什么?

【问题讨论】:

    标签: node.js jestjs


    【解决方案1】:

    在 Jest 中,当您测试应该抛出错误的情况时,在被测函数的 expect() 包装中,您需要提供一个额外的箭头函数包装以使其工作。即

    错误(但大多数人的逻辑方法):

    expect(functionUnderTesting();).toThrow(ErrorTypeOrErrorMessage);
    

    对:

    expect(() => { functionUnderTesting(); }).toThrow(ErrorTypeOrErrorMessage);
    

    这很奇怪,但应该可以成功运行测试。

    【讨论】:

    • 文档状态:Note: You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail.我同意它的用法是出乎意料的jestjs.io/docs/expect#tothrowerror
    【解决方案2】:

    Jest docs say:

    如果你想测试一个特定的错误是否被抛出,你可以为 toThrow 提供一个参数。参数可以是错误消息的字符串、错误的类或应该与错误匹配的正则表达式。

    所以你应该这样编码:

            expect(sc.getTemplateName).toThrow('foo');
    

    或者:

            expect(sc.getTemplateName).toThrow(Error);
    

    更新:更正了 expect 参数。

    【讨论】:

    • 文件包含:expect(sc.getTemplateName()).toThrow(Error);
    • expect(sc.getTemplateName()).toThrow('message'); 失败
    • 对不起,我已经更正了代码:你必须将函数传递给expect而不调用它。
    • 请填写您的答案。两种情况。而且,......你能解释更多关于语法的信息吗?对不起:我来自其他语言,...我真的不知道“foo.bar”、“foo.bar()”和“() => {foo.bar();}”的区别
    • 我所做的是更改函数调用:sc.getTemplateName(),并带有函数引用:sc.getTemplateName。所以我将函数传递给expect,它可能会使用自己的try / catch 包装器调用该函数,以便能够将生成的错误与您在toThrow 参数中提供的内容相匹配(错误消息或错误班级)。 foo.bar 是函数引用,foo.bar() 是函数调用,() => {foo.bar();} 是包含函数调用的函数。
    【解决方案3】:

    Jest 20.x.x 以下的版本,不支持您使用的语法。据说此功能“即将推出”。

    与此同时,您可以执行以下操作:

    同步示例:

    try {
      expect(sc.getTemplateName())
    } catch(e) {
      expect(e.message).toBe('foo')
    }
    

    异步示例:

    await expect(sc.getTemplateName()).toMatchObject({message: 'foo'})
    

    【讨论】:

    • 您能否提供一个链接,指向该功能“即将推出”的位置?谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 2022-10-21
    • 1970-01-01
    • 2021-09-07
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    相关资源
    最近更新 更多