【问题标题】:Testing Backbone.js Model save using Sinon not calling success callback使用Sinon测试Backbone.js模型保存不调用成功回调
【发布时间】:2012-03-15 18:29:58
【问题描述】:

我正在使用 Jasmine 和 Sinon 测试一个 Backbone.js 应用程序。我正在尝试验证单击按钮单击调用模型的 save() 方法并处理成功回调,该回调将消息添加到视图的 el 元素。我无法让 sinon 服务器触发模型的成功回调。

这就是我的规范的 beforeEach 的样子(beforeEach 中的变量都是在 describe 函数中的 var 范围)。

beforeEach(function(){
    server = sinon.fakeServer.create(); //create the fake server
    server.respondWith([200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"]); //fake a 200 response

    loadFixtures('signup_modal.html'); //load the fixture

    element = $("#signupModal");
    specSignUp = new SignUp();
    signUpView = new SignUpView({model : specSignUp, el: $("#signupModal")});
});

这就是实际测试的样子:

it("Should call send request",function(){

    element.find("#signupButton").trigger('click'); //click the button which should trigger save

    server.respond(); //fake the response which should trigger the callback

    expect(element).toContain("#message");
});

在尝试构建它的实现时,我创建了一个简单的回调方法来告诉我成功回调是被触发的:

sendRequest: function(){
    console.log("saving");
    this.model.save(this.model.toJSON(),{success: function(data){
        console.log("success");
        iris.addMessage(this.$("#messageContainer"),"Thank you");
    }});
}

当我运行测试时,控制台显示“正在保存”,但没有调用成功回调。

【问题讨论】:

  • 错误回调是否被调用?
  • 啊哈!错误被调用!我从没想过要找那个。

标签: javascript backbone.js jasmine sinon


【解决方案1】:

Backbone 期望响应文本是有效的 JSON,并且由于 server.respondWith() 方法中的响应“OK”而被轰炸。

将方法更改为:

server.respondWith([200, {"Content-Type":"text/html","Content-Length":2}, '{"OK":"True"}']);

成功回调正在成功处理。

【讨论】:

  • 这不是完全浪费,@abraham 的评论让我走上了正确的道路。没有它,我认为我不会很快得到结果。但是,是的,它总是让你感动!
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-12
  • 2017-01-15
  • 1970-01-01
相关资源
最近更新 更多