How to unit test AJAX Requests with QUnit and Sinon.JS

We write QUnit tests for Close.io, a big Backbone.js app, to help avoid introducing bugs. Pretty quickly when testing front-end JavaScript code you’ll have to deal with how to test asynchronous callbacks and especially code related to AJAX/XHR requests and how their responses are handled. Here are some basic examples of how to use Sinon.JS to handle this.

Mocking Responses

Have some code that relies on an API response coming back that you want to test? Here’s an example of mocking out the HTTP response to test a Backbone.js Model#fetch() method.

Testing Requests

But what about testing the actual request side of things? A lot of basic tutorials leave this side of the XHR out. When dealing with complicated code it can be non-trivial to determine how the AJAX request is formed, so of course you should test it!

Here’s an example testing that a Backbone.js Model#save() method produces the HTTP request that’s expected. In the real world, the Model would be much less trivial. It relies on the useFakeXMLHttpRequest feature of sinon.

To get more advanced, you can learn about mocks, stubs, and spys in the Sinon.JS documentation.

Follow @philfreo on Twitter

Want to know when I write another post? (very infrequent)

3 Comments

  1. Tarjei Huse said,

    December 18, 2012 @ 5:31 am

    Why not use buster.js?

  2. Phil Freo said,

    December 18, 2012 @ 9:44 am

    Because lots of JS projects use QUnit, and buster.js just uses Sinon.js itself anyways, so I’m not sure why you’re even asking.

  3. Asad Raza said,

    July 5, 2013 @ 1:09 am

    Thanks for your article! It helped me in making out how to fake/mock XHR calls while testing Backbone based application.

RSS feed for comments on this post