这个琐碎的类只是一个例子...
class SomeClass{
getTemplateName() {
throw new Error('foo');
}
}
Run Code Online (Sandbox Code Playgroud)
...以尝试测试某些代码引发异常
describe('dome class', () => {
test('contains a method that will throw an exception', () => {
var sc = new SomeClass();
expect(sc.getTemplateName()).toThrow(new Error('foo'));
});
});
Run Code Online (Sandbox Code Playgroud)
但不起作用。我做错了什么?
小智 26
在 Jest 中,当您测试应该抛出错误的情况时,在被测函数的 expect() 包装中,您需要提供一个额外的箭头函数包装才能使其工作。IE
错误(但大多数人的逻辑方法):
expect(functionUnderTesting();).toThrow(ErrorTypeOrErrorMessage);
Run Code Online (Sandbox Code Playgroud)
对:
expect(() => { functionUnderTesting(); }).toThrow(ErrorTypeOrErrorMessage);
Run Code Online (Sandbox Code Playgroud)
这很奇怪,但应该使测试成功运行。
如果要测试引发特定错误,可以为toThrow提供参数。参数可以是错误消息的字符串,错误的类或应与错误匹配的正则表达式。
所以你应该这样编码:
expect(sc.getTemplateName).toThrow('foo');
Run Code Online (Sandbox Code Playgroud)
要么:
expect(sc.getTemplateName).toThrow(Error);
Run Code Online (Sandbox Code Playgroud)
更新:更正的expect参数。
| 归档时间: |
|
| 查看次数: |
2844 次 |
| 最近记录: |