travis jeffery


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
      Backbone.history.stop()
      sinon.spy(Backbone.history, "start")
      App.initialize {}

      expect(Backbone.history.start).toHaveBeenCalled()

      Backbone.history.start.restore()

Source

Addition of Backbone.history.stop()