Backbone.js applications are quite amenable to testing separation. Backbone.js provides a small number of core components that mostly avoid interdependencies. Our goal in this section is to identify the different parts of a Backbone.js application that can be unit tested in isolation and start thinking about the features of each one that we should test. Many components can simply be instantiated alone while others will need some extra mocking or patching help in our tests.
Backbone.js models most often are independent entities that can be instantiated with a simple new MyModel({foo: 123})
invocation. Accordingly, we can create standalone model objects in our tests without references to any other objects. Our model tests should include the assertions that:
localStorage
or a REST server)Collections customarily have a single dependency on a model, declared like model: MyModel
in the class definition. We can either directly instantiate collections in our tests or mock the model
property for further test isolation. A typical set of collection specs should verify that:
Although templates are not an actual Backbone.js component, there are several conventional template development techniques for Backbone.js integration that we'll observe. Templates generally do not have any dependencies and can readily be used alone in test code.
The specifics of template tests largely depend on the engine used (for example, Underscore.js or Handlebars). A reasonable test starting point would confirm that:
Views frequently have the most dependencies of any Backbone.js component. Views can contain combinations of model, collection, template, router, and child/helper view references. Accordingly, we will have to mock or patch dependencies to isolate views and/or provide partial dependencies in our tests.
For all application views, we will want to verify that:
el
property get added to the DOM on creationRouters commonly contain several top-level views and may have collection or model references. For unit-testing purposes, we will usually mock out dependencies to easily test the routing behavior without regard to the rest of the application. Our router tests will need to assert that:
18.191.60.249