【问题标题】:Testing backbone router with jasmine and sinon. Cannot call the pushState.用 jasmine 和 sinon 测试骨干路由器。无法调用 pushState。
【发布时间】: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


    【解决方案1】:

    您正在测试的似乎是 Backbone 代码,但您无需对其进行测试:大概 Jeremy Ashkenas 已经对 Backbone 代码进行了大量测试(如果您查看 GitHub 上的 Backbone 项目,您会看到他确实有一个全面的测试套件)。因此,与其重新测试你没有编写的已经测试过的代码,你真正应该测试的是编写的代码。

    如果您同意该原则,那么您可以大大简化您的测试,只需:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 2012-08-10
      • 1970-01-01
      • 2012-08-10
      • 1970-01-01
      相关资源
      最近更新 更多