Testing routers in backbone.js properly?

前端 未结 6 924
太阳男子
太阳男子 2021-01-30 13:56

So I\'ve just started to write tests for my in-progress javascript app, using sinon.js & jasmine.js. Works pretty well overall, but I need to also

6条回答
  •  醉酒成梦
    2021-01-30 14:23

    When I'm testing a backbone router, what I care about is that the routes I provided are invoking the functions I specify with the correct arguments. A lot of the other answers here aren't really testing that.

    If you need to test the functionality of some routes, you can test those functions by themselves.

    Assuming you have a simple router:

    App.Router = Backbone.Router.extend({
      routes: {
        '(/)':'index',
        '/item/:id':'item'
      },
      index: {
        //render some template
      }, 
      item: {
        //render some other template, or redirect, or _whatever_
      }
    });
    

    Here's how I do it:

    describe('Router', function() {
    
      var trigger = {trigger: true};
      var router
    
      beforeEach(function() {
        // This is the trick, right here:
        // The Backbone history code dodges our spies
        // unless we set them up exactly like this:
        Backbone.history.stop(); //stop the router
        spyOn(Router.prototype, 'index'); //spy on our routes, and they won't get called
        spyOn(Router.prototype, 'route2'); 
    
        router = new App.Router(); // Set up the spies _before_ creating the router
        Backbone.history.start();
      });
    
      it('empty route routes to index', function(){
        Backbone.history.navigate('', trigger);
        expect(router.index).toHaveBeenCalled();
      });
    
      it('/ routes to index', function(){
        router.navigate('/', trigger);
        expect(router.index).toHaveBeenCalled();
      });
    
      it('/item routes to item with id', function(){
        router.navigate('/item/someId', trigger);
        expect(router.item).toHaveBeenCalledWith('someId');
      });
    });
    

提交回复
热议问题