It is no secret that at SupportBee we are big fans of test driven development. Not only do we test our Rails’ code using Rspec but we love using Jasmine to test drive our Backbone.js powered frontend. To be able to test the UI logic in isolation (that is without a backend), we heavily use mocks/stubs and also fake XML HTTP requests. We use the wonderful Sinon.js for this. Checkout this great tutorial to get started with Sinon.js for Backbone testing.
However using Sinon.js can get a little verbose at times. For example, to fake a network call that returns two tickets in the response, the setup would look something like
If you want to return more tickets, hand writing the response starts getting very cumbersome. You also have to write teardown code to cleanup after the test has run. Same way, writing mocks to test even simple logic is very tedious. For instance if you have some code that creates an Archive object for a ticket and saves it to the server (making a POST to /tickets/id/archives/), the test code would look something like
Once again, you need to restore all the mocks to make sure they don’t interfere with subsequent tests.
Finally, even if you are not testing network calls, it gets pretty cumbersome to keep writing Backbone objects to test rendering/re-rendering and event binding code. Enter Backbone Factory and a bunch of helpers :)
Backbone Factory is a Factory Girl inspired library for creating Backbone.js objects. For instance you can register a Ticket factory (that gives you instances of SB.Models.Ticket class) with this syntax
You can define sequences and use other factories to define a factory. You can use your new factory in a couple of ways
You can now easily create Backbone objects without having to worry about unique ids etc. It is all taken care for you.
Helpers for setting up/verifying/tearing down mocks
Since a lot of tests involve setting up and verifying a bunch of mocks, we wrote a test helper to simplify things. Using it you can write test code like
You can specify the number of times a mock should be called or pass times:0 to make sure the mock is never called. The setup and tear down is automatically taken care for you. Helpers for setting up setting up fake servers and responses The final component helps us easily create fake XMLHTTP servers and responses. It uses the factories that you have already defined to setup responses. For example
This helper currently only deals with GET requests and you have to manually call .respond() and .restore() since there is no easy way to figure out when you are done using the fake server.
You can find the helpers on github. Unfortunately they are not test driven (duh!).
Putting everything together, you can write tests like these
As I said we do use a lot of mocks/fake responses but so far the tests have been pretty maintainable. Also they run really fast. If you find a bug or improve the helpers, do send a pull request!