我想为metadataLoaded
承诺编写测试,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");
});
});
答案 0 :(得分:0)
方法和测试用例中的“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();
}
});
// ...
});
答案 1 :(得分:0)
感谢@Skay,这是有效的:
str