我正在关注这个问题来测试路由器。我的路由器非常简单:
App.Router = Backbone.Router.extend({
routes:{
"": "index",
"help": "help"
},
help: function() {/* not really needed */ },
index: function(){
// does something
}
});
这是对使用 jasmine 和 sinon 的测试应该是什么的试探性翻译:
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 是否有意义(记住我添加“帮助”只是为了让这个测试通过,所以我不需要它)?如果它确实有意义,我怎样才能完成这个测试?