Customizer APIs in 4.6 for Setting Validation and Notifications
Test-driven Development of a Backbone.js App. Part 2.
Please note that you will find all 3 parts of this article as well as the source code of the tutorial in the project’s GitHub repository.
Implementing Backbone.js Model
In the first part of the series I walked you through the test-driven development concepts. Then we have set up the project workspace, including a QUnit test runner and an empty source files accompanied with test files.
In the second part of the article, we will create our first Backbone.js model using TDD principles.
Early on in the project I decided to use the Backbone.js library and build our ControlColor
component on top of it. In this case, first, we have to make sure that we’re dealing with a Backbone model.
To do so, we can look into object’s prototype and search for e.g. fetch
and sync
methods, which are pretty specific to Backbone models:
QUnit.module( 'models/control-color.js', function() {
QUnit.test( 'Color control exists and is Backbone model', function( assert ) {
var Model = window.ControlColor;
assert.ok( ! _.isUndefined( Model ), 'model is defined' );
assert.ok( _.isFunction( Model.prototype.fetch ) && _.isFunction( Model.prototype.sync ), 'model is Backbone model' );
} );
} );
If we run unit tests now (refresh the browser), we will get one failing test:
Tests completed in 10 milliseconds.
1 assertions of 2 passed, 1 failed.
To fix it, we have to make ControlColor
a real Backbone model:
window.ControlColor = Backbone.Model.extend( {} );
Now both tests are passing, so we have successfully gone through the green phase. There is nothing to refactor at this point, so we’re skipping this step.
Our new Backbone model has to store an array of available options and an array of currently selected options. So let’s write some tests to describe those requirements:
QUnit.module( 'models/control-color.js', function() {
...
QUnit.test( 'Model has required properties', function( assert ) {
var model = new window.ControlColor();
assert.ok( model.has( 'options' ), 'model has "options" property' );
assert.ok( _.isArray( model.get( 'options' ) ), '"options" is array' );
assert.ok( model.has( 'checked' ), 'model has "checked" options property' );
assert.ok( _.isArray( model.get( 'checked' ) ), '"checked" options is array' );
} );
} );
All 4 tests are failing, so we’re good to proceed to green phase. Note that in this set of tests, we’ve already initialized the ControlColor
model so that we can use Backbone methods like has()
or get()
.
To make tests pass, let’s define defaults property in the ControlColor
model:
window.ControlColor = Backbone.Model.extend( {
defaults: {
options: [],
checked: []
}
} );
Tests are green now. Again we won’t refactor neither implementation nor testing code.
Continue reading Test-driven Development of a Backbone.js App. Part 2.