Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to unit test the backbone success and error response on save using jasmine

 onSaveEvent: function (event) {
                if (this.model !== null) {
                    var that = this;

                    this.model.save(this.model.toJSON(), {
                        success: function (model) {
                            that.model = model;
                            that.model.attributes.isDirty = false;
                        },

                        error: function (model, xhr) {
                            that.model.attributes.isDirty = true;
                        }
                    });
                }
            }
        }

how to unit test the model's save' success and error responses in Jasmine?

like image 675
Gururaj Avatar asked Oct 21 '22 10:10

Gururaj


2 Answers

To test this without a fake server you can test that the function was binded to the model an then call the binded function by yourself. In other words mock out the ajax save part out of the model.

var view = new YourView()
jasmine.spyOne(view.model, 'save')
view. onSaveEvent()
var args = view.model.save.mostRecentCall.args

args[1].success()
expect(view.model.attributes.isDirty).toBeFalsy()

args[1].error()
expect(view.model.attributes.isDirty). toBeTruthy()
like image 172
Andreas Köberle Avatar answered Oct 24 '22 03:10

Andreas Köberle


You can use Sinon.js to create a fake server for your tests.

http://sinonjs.org/

Example code:

  describe("when saving a user model", function() {

    beforeEach(function() {
      this.server = sinon.fakeServer.create();
      this.responseBody = '{"name":"test user","id":1,"title":"tester"}';
      this.server.respondWith(
        "POST",
        "/user",
        [
          200,
          {"Content-Type": "application/json"},
          this.responseBody
        ]
      );
      this.eventSpy = sinon.spy();
    });

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

    it("should not save when name is blank", function() {
      this.user.bind("error", this.eventSpy);
      this.user.save({"name": ""});

      expect(this.eventSpy).toHaveBeenCalledOnce();    
      expect(this.eventSpy).toHaveBeenCalledWith(this.user, "cannot have a blank name");
    });

    it("should call the server", function() {
      this.user.save();
      expect(this.server.requests[0].method).toEqual("POST");
      expect(this.server.requests[0].url).toEqual("/user");
      expect(JSON.parse(this.server.requests[0].requestBody)).toEqual(this.user.attributes);
    });

  });
like image 24
Scott Puleo Avatar answered Oct 24 '22 02:10

Scott Puleo