【发布时间】:2013-06-25 05:46:12
【问题描述】:
我正在关注这个question 来测试路由器。我的路由器真的很简单:
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 是否有意义(请记住,我添加“帮助”只是为了使此测试通过,所以我不需要它)?如果它确实有意义,我该如何完成这个测试?
【问题讨论】:
标签: backbone.js jasmine backbone-routing sinon