Chapter 15. SinonJS

Similar to the section on testing Backbone.js apps using the Jasmine BDD framework, we’re nearly ready to take what we’ve learned and write a number of QUnit tests for our Todo application.

Before we start, though, you may have noticed that QUnit doesn’t support test spies. Test spies are functions that record arguments, exceptions, and return values for any of their calls. They’re typically used to test callbacks and how functions may be used in the application being tested. In testing frameworks, spies usually are anonymous functions or wrappers around functions that already exist.

What Is SinonJS?

In order for us to substitute support for spies in QUnit, we will be taking advantage of a mocking framework called SinonJS by Christian Johansen. We will also be using the SinonJS-QUnit adapter, which provides seamless integration with QUnit (meaning setup is minimal). SinonJS is completely test-framework−agnostic and should be easy to use with any testing framework, so it’s ideal for our needs.

The framework supports three features we’ll be taking advantage of for unit testing our application:

  • Anonymous spies

  • Spying on existing methods

  • A rich inspection interface

Basic Spies

Using this.spy() without any arguments creates an anonymous spy. This is comparable to jasmine.createSpy(). We can observe basic usage of a SinonJS spy in the following example:

test('should call all subscribers for a message exactly once', function () {
    var message = getUniqueString ...

Get Developing Backbone.js Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.