Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.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 当带有arg的函数抛出时,QUnit终止,除非包装在anon函数中_Javascript_Testing_Anonymous Function_Qunit - Fatal编程技术网

Javascript 当带有arg的函数抛出时,QUnit终止,除非包装在anon函数中

Javascript 当带有arg的函数抛出时,QUnit终止,除非包装在anon函数中,javascript,testing,anonymous-function,qunit,Javascript,Testing,Anonymous Function,Qunit,我正在使用QUnit测试一个函数,该函数在输入无效的情况下抛出错误。我可以通过将它嵌入匿名函数来测试这个函数,但我不确定为什么这是必要的。如果我不这样做,QUnit报告: Died on test #4 at http://localhost:8000/qunit/throwsTest.js:1:7: sometimesThrows 值得注意的是,此消息包含抛出的错误 我还注意到,如果我将函数作为参数传递而不是调用它,我可以使不需要参数的函数工作 去现场看看吧 QUnit.test("

我正在使用QUnit测试一个函数,该函数在输入无效的情况下抛出错误。我可以通过将它嵌入匿名函数来测试这个函数,但我不确定为什么这是必要的。如果我不这样做,QUnit报告:

Died on test #4     at http://localhost:8000/qunit/throwsTest.js:1:7: sometimesThrows
值得注意的是,此消息包含抛出的错误

我还注意到,如果我将函数作为参数传递而不是调用它,我可以使不需要参数的函数工作

去现场看看吧

QUnit.test("throws test", function(assert) {
  function alwaysThrows() { throw "alwaysThrows"; }

  function sometimesThrows(foo) {
    if (foo) {
      return true;
    }
    else {
      throw "sometimesThrows";
    }
  }

  assert.throws(alwaysThrows, "alwaysThrows throws (works)")

  assert.ok(sometimesThrows(true), "sometimesThows doesn't throw (works)");
  assert.throws(function() {
    sometimesThrows(false);
  }, "sometimesThrows throws inside anonymous function (works)");

  // Where the unexpected behavior occurs.
  // The error _is_ being thrown being thrown.
  assert.throws(sometimesThrows(false), "sometimesThrows throws (terminates)");

});

如果将要测试的函数包装在匿名函数中是实现此功能的预期方法,如果有人能够解释原因,我会发现这对我的直觉发展很有启发。

TL;DR:这正是计划工作的方式,也是它必须工作的方式

冗长的回答:

在您的示例中,您使用调用
sometimesThrows(false)
结果调用断言。也就是说,在上面的示例中,当调用QUnit assert方法(
assert.throws()
)时,传入两个值:来自
sometimesThrows()
返回值和字符串消息

换句话说,您的示例:

assert.throws(sometimesThrows(false), "sometimesThrows throws (terminates)");
首先使用
false
参数调用
sometimesThrows()
方法,该参数立即执行该方法,从而引发错误。但这一错误会走向何方??事实上,该错误是从您的方法(
sometimesThrows()
)直接抛出到您编写的
test()
,完全绕过
assert.throws()
调用。换句话说,
assert.throws()

相反,我们必须传递
assert.throws()
函数另一个函数,然后它可以将该函数包装在
try…catch
块中,以检测是否抛出了错误。如果您愿意,我们可以将其分离出来,并实际传入一个命名函数(相对于匿名内联函数),但这实际上不会改变任何事情:

测试(“抛出测试”,函数(断言){ //

function sometimesWrapper() {
    sometimesThrows(false);
}

assert.throws(sometimesWrapper, "sometimesThrows throws (terminates)");
}))


请注意,我们不调用
sometimesWrapper()
,而是将其作为参数传递给
throws()
断言方法。在内部,QUnit将把
sometimesWrapper()
的实际调用包装在
try…catch
块中,以便确定断言是通过还是失败。如果您愿意,您可以在中看到这一点。

这很有道理。非常感谢您澄清这一行为!