I would like to hear other people's opinion on how I unit tested a functionality in a Backbone Model. As you see below, the code under test, upon being called to toggle, toggles its completed state and saves the new state:
// js/models/todo.js
var app = app || {};
// Todo Model
// ----------
// Our basic **Todo** model has `title` and `completed` attributes.
app.Todo = Backbone.Model.extend({
// Default attributes ensure that each todo created has `title` and `completed` keys.
defaults: {
title: '',
completed: false
},
// Toggle the `completed` state of this todo item.
toggle: function() {
this.save({
completed: !this.get('completed')
});
}
});
To unit test this, as you can see below, I stub Backbone.sync method and make sure that the Model is saved with the correct state:
describe("todo", function() {
it("should save the toggled completed state", function() {
var stub = sinon.stub(Backbone, "sync", function(method, model) {
expect(model.get("completed")).to.equal(true);
});
var todo = new app.Todo({completed: false});
todo.toggle();
expect(stub.calledOnce).to.equal(true);
Backbone.sync.restore();
});
});