SO problems testing router

http://stackoverflow.com/questions/11847339/spying-on-backbone-js-route-calls-with-jasmine

by fguillen

HTML

<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone.js"></script>
<script src="https://raw.github.com/jeromegn/Backbone.localStorage/master/backbone.localStorage.js"></script>
<script src="http://sinonjs.org/releases/sinon-1.3.4.js"></script>
<html>
<head>
    <link href="http://blog.bandzarewicz.com/stylesheets/jasmine/jasmine.css" media="screen, projection" rel="stylesheet" type="text/css">

    <script src="https://raw.github.com/pivotal/jasmine/v1.1.0/lib/jasmine-core/jasmine.js"></script>
<script src="https://raw.github.com/pivotal/jasmine/v1.1.0/lib/jasmine-core/jasmine-html.js"></script>


  <title>Jasmine Spec Runner</title>
</head>

<body>

</body>
</html>

JavaScript

var App = {};

App.Router = Backbone.Router.extend({
  routes:{
    "": "index",
    "other_route": "otherRoute"
  },

  index: function(){
    console.log( "router.index has been called" );
  },
    
  otherRoute: function(){
    console.log( "router.otherRoute has ben called" );
  }
        
});


describe("Router", function() {
  afterEach( function(){
    Backbone.history.stop();
  });

  it("should call index", function(){
    spyOn(App.Router.prototype, "index")
    var router = new App.Router();
    Backbone.history.start();

    router.navigate('', true);
    
    expect(App.Router.prototype.index).toHaveBeenCalled();  
  });

  it("should call otherRoute", function(){
    spyOn(App.Router.prototype, "otherRoute")
    var router = new App.Router();        
    Backbone.history.start();

    router.navigate('other_route', true);    
    
    expect(App.Router.prototype.otherRoute).toHaveBeenCalled();  
  });
});




//
// Jasmine spec runner
//
(function() {
    var jasmineEnv = jasmine.getEnv();
    jasmineEnv.updateInterval = 1000;

    var trivialReporter = new jasmine.TrivialReporter();

    jasmineEnv.addReporter(trivialReporter);

    jasmineEnv.specFilter = function(spec) {
        return trivialReporter.specFilter(spec);
    };

    var currentWindowOnload = window.onload;

    window.onload = function() {
        if (currentWindowOnload) {
            currentWindowOnload();
        }
        execJasmine();
    };

    function execJasmine() {
        jasmineEnv.execute();
        trivialReporter.outerDiv.className += ' show-passed';
    }

})();