Javascript Js函数检查方法是否抛出
假设我有类Javascript Js函数检查方法是否抛出,javascript,ecmascript-6,Javascript,Ecmascript 6,假设我有类Foo和方法bar class Foo { bar() { ... } } 我需要通用函数isThrows来检查方法bar是否抛出。有可能吗?我编写了这样的函数 function isThrows(obj, method, ...args) { var result = false; try { method.apply(obj, args); } catch (e) { result = tru
Foo
和方法bar
class Foo {
bar() {
...
}
}
我需要通用函数isThrows
来检查方法bar
是否抛出。有可能吗?我编写了这样的函数
function isThrows(obj, method, ...args) {
var result = false;
try {
method.apply(obj, args);
} catch (e) {
result = true;
}
return result;
}
使用
这个问题毫无意义?您的意思是
尝试{}捕获{}
?否。我需要一个函数,它将接受方法作为参数,并检查方法是否抛出到它的主体中。用try{}catch{}。为什么?这是非常有趣的?我需要在我的测试中做很多这样的检查。我不想一次又一次地写try{}catch{}。@melihovv为什么不使用测试框架的方法来断言抛出的错误?
const foo = new Foo();
const result = isThrows(foo, foo.bar/*, additional params if needed */);