3
\$\begingroup\$

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();
 });
});
asked Aug 31, 2014 at 15:25
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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();
answered Aug 31, 2014 at 18:46
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.