Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Js函数检查方法是否抛出_Javascript_Ecmascript 6 - Fatal编程技术网

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 */);