这个简单的类只是一个例子......
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/