2013-06-27 41 views
3

我跟着这个question来测试路由器。我的路由器是非常简单的:用茉莉花和sinon测试骨干路由器。无法调用pushState。

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

    help: function() {/* not really needed */ }, 

    index: function(){ 
     // does something 
    } 
}); 

这是什么都要用茉莉花与兴农测试的apptempted翻译:

it('triggers the "index" route', function() { 
    var router = new App.Router(); 
    Backbone.history.start(); 
     //Not calling navigate it's a problem 
    router.navigate('help', { 
     trigger : true, replace: true 
    }); 
    var index = sinon.spy(router, 'index'); 

    var spyHasPS = sinon.spy(function(
      data, title, url) { 
     expect(url).toEqual('/'); 
     router.index(); 
    }); 

    var spyNoPS = sinon.spy(function(loc, frag) { 
     expect(frag).toEqual(''); 
     router.index(); 
    }); 

    if (Backbone.history._hasPushState) { 
     pushStateSpy = sinon.stub(window.history, 'pushState', spyHasPS); 
    // window.history.pushState(); 
    } else if (Backbone.history._wantsHashChange) { 
     pushStateSpy = sinon.stub(Backbone.history, '_updateHash', spyNoPS); 
     //Backbone.history._updateHash(window.location, ''); 
    } 

    router.navigate('', { 
     trigger : true, replace: true 
    }); 
    expect(pushStateSpy.called).toBe(true); 
    expect(index.called).toBe(true); 

}); 

这个测试工作,但我能做到,因为我导航先上“帮帮我”。 “帮助”只是我为了通过考试而创建的,但原始问题没有做到,而且正在通过。我做错什么了吗?我也跑了测试,但我得到的错误是:

Expected spy _updateHash to have been called. Error: Expected spy 
_updateHash to have been called. 
    at null.<anonymous> (/src/test/js/spec/wfcRouter.spec.js:65:32)  Expected spy index to have been called. 

我相信“的问题”是在导航功能。在navigate: function(fragment, options)某一点上,我们有这样的控制:

fragment = this.getFragment(fragment || ''); 
    if (this.fragment === fragment) return; 

所以...它是有意义的测试pushState的时候,你只需要一个路线(记住我说的“帮助”只是为了让这个测试通过所以我不需要它)?如果确实有道理,我该如何实现这个测试?

回答

0

看起来你正在测试的是Backbone代码,但你不需要测试它:大概Backbone代码已经被Jeremy Ashkenas测试了很多(如果你看看GitHub上的Backbone项目,你会看到他确实拥有全面的测试套件)。所以,与其重新测试你没有写的测试代码,你真正应该测试的代码是,你写道。

如果该原则同意,那么您可以简化测试了很多,下到刚:

it('triggers the "index" route', function() { 
    var router = new App.Router(); 

    router.index(); 
    expect(thingThatShouldHaveHappenedInIndexRouteDidHappen).toBe(true); 
});