如何检查 qunit 中的错误

how to check error in qunit

我在 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("i18n", "error"));
        }
    });
}

如何在 qunit 中检查结果是否错误?让我们假设结果:bResultfalse 并且 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 的 async ability, otherwise the test function finishes before your promise is resolved. Additionally, you can use the throws assertion 来检查错误。下面的示例使用的是 QUnit 版本 1.16.0(最新版本)。

validateOnSelection : function(model) {
    // Instead, return a promise from this method which your calling code can use:
    var deferred = Q.defer();

    this.context.service.doLofig(model).then(function(bResult) {
        if (bResult) {
            // return true; this doesn't really do anything, it doesn't return anywhere.
            // instead, resolve the promise:
            deferred.resolve(true);
        } else {
            // we don't really want to "throw" here, we nee to reject the promise:
            // throw new Error(that.context.i18n.getText("i18n", "error"));
            deferred.reject(new Error(that.context.i18n.getText("i18n", "error")));
        }
    });

    return deferred.promise;
}

现在我们可以设置我们的测试来等待承诺完成然后测试结果...

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.
    });
});