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?
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()
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With