With a Backbone.js application integrated into our budding test infrastructure and a rough test plan underway, we will now begin expanding our application's test coverage. In this chapter, we will introduce some fundamental testing tools and test more parts of the Backbone.js application in the following topics:
Surveying the Mocha and Chai test library interfaces and styles
Introducing the Chai assertion library API
Configuring the Mocha runner and the Backbone.js application for tests
Aggregating Mocha specifications into test suites and preparing test state
Writing test specifications in Mocha, beginning with Backbone.js collection specs
Testing asynchronous application code
Writing specs and HTML test fixtures for Backbone.js views
Dealing with software/test development pitfalls and learning how to write testable code
Choosing a test style that fits
Mocha and Chai both provide different library interfaces for writing tests. This conveniently allows developers to choose an appropriate test paradigm or style for different projects while still leveraging the same underlying functionality.
Mocha test interfaces
Mocha currently offers four interfaces for test suites and specifications:
The Behavior-Driven Development (BDD) interface: This interface uses test constructs similar to those popularized by the Ruby RSpec framework (http://rspec.info/).
TheTest-Driven Development (TDD) interface: This interface uses more traditional unit test keywords such as suite and test.
The exports interface: This interface utilizes a modular format familiar to Node.js/CommonJS developers, implementing the test functionality as properties of a module.exports object.
The QUnit-styled interface: This interface uses a flat declaration paradigm taken from the popular QUnit test framework (http://qunitjs.com/). A suite in this style is declared before and at the same level as a test instead of containing tests like the other interfaces just discussed.
Chai assertion styles
Chai provides two assertion styles:
TheBDD style: This style enables dot-notation chains of assertions such as expect("foo").to.be.a("string").and.equal("foo") using either the expect function or the should object prototype extension
The assert style: This style uses single function assertions attached to the assert object, such as:
Although expect and assert are functionally equivalent, there are some important differences between the BDD constructs expect and should. Essentially, because should patches the object prototype, it will not work for certain types of actual values (such as null and undefined) and is incompatible with Internet Explorer 9. For these reasons, our Chai BDD examples will use expect over should.