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();
});
});
1 Answer 1
I'm not really familiar with mocha. If I understand correctly, the true
and false
values here closely releated, in the sense that they should be opposites:
var stub = sinon.stub(Backbone, "sync", function(method, model) { expect(model.get("completed")).to.equal(true); }); var todo = new app.Todo({completed: false});
In that case, to avoid mistakes, it would be better to include that logic in the code, for example:
var initial_state = false;
var stub = sinon.stub(Backbone, "sync", function(method, model) {
expect(model.get("completed")).to.equal(initial_state);
});
var todo = new app.Todo({completed: !initial_state});
And maybe add another test for the inverse, for initial_state = true
.
Instead of this:
var todo = new app.Todo({completed: false}); todo.toggle();
Since you only use the todo
instance once, I would combine the two lines to shorten the code:
new app.Todo({completed: false}).toggle();
Instead of this .to.equal(true)
:
expect(stub.calledOnce).to.equal(true);
I think it would be more natural (and shorter) with .to.be.ok()
:
expect(stub.calledOnce).to.be.ok();
Explore related questions
See similar questions with these tags.