如何在 SAPUI5 中的 sinon.stub().resolves() 之后使 qUnit 断言?

How to make qUnit assert after sinon.stub().resolves() in SAPUI5?

我想为 metadataLoaded promise 写测试,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");
    });
});

方法中和测试用例中的"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();
        }
    });
    // ...
});

感谢@Skay,这是有效的:

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