Javascript 如何检查qunit中的错误
我有一个JavaScript函数,它使用Javascript 如何检查qunit中的错误,javascript,qunit,q,Javascript,Qunit,Q,我有一个JavaScript函数,它使用q库: validateOnSelection : function(model) { this.context.service.doLofig(model).then(function(bResult) { if (bResult) { return true; } else { throw new Error(that.context.i18n.getText("i
q
库:
validateOnSelection : function(model) {
this.context.service.doLofig(model).then(function(bResult) {
if (bResult) {
return true;
} else {
throw new Error(that.context.i18n.getText("i18n", "error"));
}
});
}
我怎样才能确认结果是错误的?让我们假设结果:bResult
是false
,并且Error
应该引发
我试过:
test("Basic test ", {
// get the oTemplate and model
return oTemplate.validateOnSelection(model).then(function(bResult) {
// Now I need to check the error
});
}));
我没有进行检查的问题“//现在我需要检查错误”这里有很多问题。首先,您没有任何方法让调用代码知道您的函数已经完成。如果没有这些,QUnit就无法确定何时运行断言。然后您将需要使用QUnit,否则测试函数将在您的承诺得到解决之前完成。此外,还可以使用来检查错误。下面的示例使用的是QUnit版本1.16.0(最新版本) 现在我们可以设置测试,等待承诺完成,然后测试结果
QUnit.test("Basic test", function(assert) {
// get the oTemplate and model
var done = QUnit.async(); // call this function when the promise is complete
// where does `model` come from???
oTemplate.validateOnSelection(model).then(function(bResult) {
// Now I need to check the error
assert.ok(bResult instanceof Error, "We should get an error in this case");
done(); // now we let QUnit know that async actions are complete.
});
});
您不需要函数来使用返回语句吗?:)是的,那里有很多错误,我现在正在写一个答案…@jakerella好的。我不会费心做同样的事别忘了提到
asyncTest、stop、start和throws
:)实际上,asyncTest
从1.16.0开始就被弃用了。如何使用抛出?错误是validateSelection中的riase,我想在qunit中捕获它。我无法更改ValidateSelection的逻辑。鉴于您的设置,您不应使用throws
。validateOnSelection()
方法是异步的,因为它有承诺,所以您需要让QUnit知道事情何时完成。这需要通过另一个承诺(正如我向您展示的)或回调来实现。如果您无法更改该逻辑,那么如果该方法确实是异步的,则无法测试该方法。您无法确定函数何时完成。QUnit将在函数返回之前完成测试。为什么我需要使用q.defer?
QUnit.test("Basic test", function(assert) {
// get the oTemplate and model
var done = QUnit.async(); // call this function when the promise is complete
// where does `model` come from???
oTemplate.validateOnSelection(model).then(function(bResult) {
// Now I need to check the error
assert.ok(bResult instanceof Error, "We should get an error in this case");
done(); // now we let QUnit know that async actions are complete.
});
});