测试Backbone.js模型保存使用Sinon不调用成功回调

Testing Backbone.js Model save using Sinon not calling success callback

本文关键字:Sinon 调用 成功 回调 Backbone js 模型 保存 测试      更新时间:2023-09-26

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

以下是我的规范的beforeEach的样子(beforeEah中的变量都是描述函数中的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");
});

在尝试构建此实现的同时,我创建了一个简单的回调方法,向我展示成功回调是由beign触发的:

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

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

Backbone希望响应文本是有效的JSON,但由于server.respondWith()方法中的响应"OK"而被炸飞。

将方法更改为:

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

正在成功处理成功回调。