2013-06-27 57 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); 
});