Backbone.js Sinonjs:如何模拟主干获取
我使用主干,在accountsView.js中具有以下功能:Backbone.js Sinonjs:如何模拟主干获取,backbone.js,sinon,Backbone.js,Sinon,我使用主干,在accountsView.js中具有以下功能: loadData: function () { this.accountsCollection.fetch() .done(_.bind(this.loadDefaultAccounts, this)) .fail(_.bind(this._accountsLoadFailed, this)); }, 在qunit测试中,我试图
loadData: function () {
this.accountsCollection.fetch()
.done(_.bind(this.loadDefaultAccounts, this))
.fail(_.bind(this._accountsLoadFailed, this));
},
在qunit测试中,我试图这样模拟它:
sandbox.stub(Backbone.Collection.prototype, "fetch").yieldsTo("done", {});
loadData: function () {
this.accountsCollection.fetch({
success: _.bind(this.loadDefaultAccounts, this),
error: _.bind(this._accountsLoadFailed, this),
});
},
但在运行测试时出现以下错误:
“fetch应屈服于'done',但没有具有此类属性的对象。”
通过了。”
我错过了什么?
yieldsTo
在我看来,它是用来处理基于回调的代码的
要模拟AJAX请求,您应该设置一个
this.server.respondWith("GET", "/some/article/comments.json",
[200, { "Content-Type": "application/json" },
'[{ "id": 12, "comment": "Hey there" }]']);
谢谢你的提示。为了使我的测试工作正常,视图中的函数应如下所示:
sandbox.stub(Backbone.Collection.prototype, "fetch").yieldsTo("done", {});
loadData: function () {
this.accountsCollection.fetch({
success: _.bind(this.loadDefaultAccounts, this),
error: _.bind(this._accountsLoadFailed, this),
});
},
或者在测试中使用@TJ建议的假服务器
.fetch
函数接受一个选项
对象,在该对象中,您可以使用上下文
传递成功
和错误
回调。e、 g..fetch({context:this,success:this.loadDefaultAccounts})代码>