How-to test starting backbone's history

Backbone.history.start() can be only be called once, doing otherwise will cause an Error to be thrown with the message “Backbone.history has already been started”.

This can be annoying when testing because it’s common practice to have an App namespace that contains a initializer method to setup your application, including starting Backbone’s history.

App =
  initialize: (data) ->
    # ...
    if not Backbone.history.started?
      Backbone.history.start({pushState: true})
      Backbone.history.started = true

But each test case you write that calls this initializer method will also call Backbone.history.start(). The solution is use Backbone.history.stop() which will disable history temporarily.

describe "App", ->
  describe "#initialize", ->
    it "starts Backbone.history", ->
      Backbone.history.started = null
      sinon.spy(Backbone.history, "start")
      App.initialize {}




Addition of Backbone.history.stop()

Follow me on Twitter to keep up with what I’ve learned building my personal finance tool, Stash.

Read more posts …
Written: April 16th, 2012
Categories: backbone, backbonejs, history, start, testing