node.js - 开 Jest : test that exception will be thrown isnt working

标签 node.js jestjs

这个简单的类只是一个例子......

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'));
    });
});

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

最佳答案

在 Jest 中,当您测试应抛出错误的情况时,在测试中的函数的 expect() 包装中,您需要提供一个额外的箭头函数包装,以便实现它上类。即

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

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

右:

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

这很奇怪,但应该能使测试成功运行。

关于node.js - 开 Jest : test that exception will be thrown isnt working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49027595/

相关文章:

node.js - Mongodb:仅当该对象的元素唯一时才将对象插入到数组中

node.js - 使用 q.map 时如何避免破坏 promise 链?

node.js - 从 Node-webkit 运行 Protractor

node.js - Express 中间件 : allow access to only admin or moderator

javascript - 测试嵌套的 React 组件

unit-testing - 在 Jest 测试中获得 axios 响应后如何重新渲染

javascript - node.js并行执行

reactjs - Jest/ enzyme 测试事件监听器已删除

gitlab - 未找到开 Jest 测试

javascript - 用 Jest 在 javascript 中模拟类原型(prototype)