【问题标题】:How to mock an error callback for a BackboneJS model (in destroy)?如何模拟 BackboneJS 模型的错误回调(在销毁中)?
【发布时间】:2013-12-09 11:32:15
【问题描述】:

鉴于以下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 进行测试。

【问题讨论】:

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


    【解决方案1】:

    如果您想测试错误回调...您可以使用 http://sinonjs.org/ 在 jasmine 中模拟服务器响应

    在 before 块中定义你的服务器:

    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.
      });
    });
    

    【讨论】:

    • 你有没有机会在不涉及服务器的情况下模拟 客户端 Product 模型的响应?
    • 此方法不涉及真实服务器。
    • 明白。不过,我想避免这种情况。
    • 如果你不想使用任何库,你可以存根 $.ajax 方法。像这样:htmlgoodies.com/html5/javascript/…
    猜你喜欢
    • 1970-01-01
    • 2015-04-15
    • 2020-01-03
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 2020-02-20
    相关资源
    最近更新 更多