【问题标题】:How to make qUnit assert after sinon.stub().resolves() in SAPUI5?如何在 SAPUI5 中的 sinon.stub().resolves() 之后使 qUnit 断言?
【发布时间】:2018-06-11 19:47:28
【问题描述】:

我要为metadataLoadedpromise写测试,sinon版本是4.1.2。

调用了 Promise resolve,但我不知道如何编写正确的测试断言。我绑定的两个断言失败了。

_onObjectMatched : function (oEvent) {
    var sObjectId =  oEvent.getParameter("arguments").objectId;
    this.getModel().metadataLoaded().then( function() {
        var sObjectPath = this.getModel().createKey("TaskSet", {
            id :  sObjectId
        });
    }.bind(this));
},

QUnit.test("_onObjectMatched", function(assert) {
    var oEventStub = {
        getParameter: sinon.stub().returns({objectId: "1"})
    };
    this.oModelStub = {
        createKey: sinon.stub().returns("key"),
        metadataLoaded :  jQuery.noop
    };
    sinon.stub(this.oModelStub, "metadataLoaded").resolves();

    this.oController._onObjectMatched(oEventStub);

    //Error: assert before promise resolves
    assert.ok(this.oModelStub.createKey.calledOnce, "createKey called");

    //Error: this.oModelStub.metadataLoaded.then is not a function
    this.oModelStub.metadataLoaded.then(function() {
        assert.ok(this.oModelStub.createKey.calledOnce, "createKey called");
    });
});

【问题讨论】:

    标签: sapui5 sinon qunit


    【解决方案1】:

    方法和测试用例中的“this”是否指向同一个对象?看起来不是。无论如何,这段代码应该可以工作:

    QUnit.test("_onObjectMatched", function(assert) {
        // ...
        // where obj - reference to the object with "_onObjectMatched" method
        sinon.stub(obj, "_onObjectMatched").returns({
            createKey: sinon.stub().returns("key"),
            metadataLoaded: function () {
                return Promise.resolve();
            }
        });
        // ...
    });
    

    【讨论】:

    • this.oController 在测试用例中等于 this 在控制器方法中。
    • 我更改了代码,但仍然返回this.oModelStub.metadataLoaded.then is not a function
    • this.oModelStub.metadataLoaded()
    【解决方案2】:

    感谢@Skay,这行得通:

    this.oModelStub.metadataLoaded().then(function() {
        assert.ok(this.oModelStub.createKey.calledOnce, "createKey called");
    }.bind(this));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-28
      • 2011-08-02
      • 1970-01-01
      • 2015-01-19
      相关资源
      最近更新 更多