如何模拟BackboneJS模型的错误回调(在destroy中)?

时间:2013-12-09 11:32:15

标签: backbone.js callback jasmine marionette backbone-model

鉴于以下BackboneJS 1.1.0 model / MarionetteJS 1.0.4 module

MyApp.module('Product', function(Product, App, Backbone, Marionette, $, _) {    
  Product.Model = Backbone.Model.extend({

    destroy: function() {
      console.log("Product.destroy()");
      return Backbone.Model.prototype.destroy.apply(this, arguments);
    }

  });
});

您如何模拟 destroy function 失败,以便您可以测试相关行为(例如用户通知提醒消息)?我在这个项目中使用Jasmine 1.3.0进行测试。

1 个答案:

答案 0 :(得分:1)

如果您想测试错误回调...您可以使用http://sinonjs.org/

模拟茉莉花中的服务器响应

在之前的块中定义您的服务器:

var server, aProductInstance;

beforeEach(function() {
  server = sinon.fakeServer.create();
  aProductInstance = new Product.Model({id: 999});
});

每次测试后恢复:

afterEach(function() {
  server.restore();
});

在测试中,使用respondWith方法返回非200响应

server.respondWith(method, url, response);

喜欢这样

describe("fail to destroy", function() {
  it("calls the error callback", function() {
    server.respondWith("DELETE", "/products/destroy", [500, { "Content-Type": "application/json" }, '{ "error": "bad request" }']);

    //call the method
    aProductInstance.destroy();

    //send the response
    server.respond();

    //now write your tests to see if error callback is called.
  });
});