How to mock an error callback for a BackboneJS model (in destroy)?

439 Views Asked by At

Given the following 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);
    }

  });
});

How would you simulate that the destroy function fails so you can test the associated behavior (such as a user notification alert message)? I use Jasmine 1.3.0 for testing in this project.

1

There are 1 best solutions below

4
On

if you wanna test the error callback...you can mock the server response in jasmine by using http://sinonjs.org/

define your server in a before block:

var server, aProductInstance;

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

restore it after each test:

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

in your test, use respondWith method to return a non-200 response

server.respondWith(method, url, response);

like so

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