正确测试backbone.js中的路由器?

Testing routers in backbone.js properly?(正确测试backbone.js中的路由器?)

本文介绍了正确测试backbone.js中的路由器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我刚刚开始使用 sinon.js & 为我正在进行的 javascript 应用程序编写测试.jasmine.js.总体上运行良好,但我还需要能够测试我的路由器.

So I've just started to write tests for my in-progress javascript app, using sinon.js & jasmine.js. Works pretty well overall, but I need to also be able to test my routers.

路由器在其当前状态下将触发许多视图和其他内容,通过调用依赖于应用程序的 Backbone.navigate 来终止当前的 jasmine.js 测试状态和 UI 迭代.

The routers, in their current state, will trigger an number of views and other stuff, terminating the current jasmine.js test by invoking Backbone.navigate dependent on application state and UI itneraction.

那么我怎样才能测试到不同位置的路由是否可行,同时保持路由器沙盒"并且不允许它们更改路由?

So how could I test that routing to different locations would work, while keeping the routers "sandboxed" and not allowing them to change route?

我可以设置某种模拟函数来监控 pushState 变化或类似情况吗?

Can I set up some sort of mock function that will monitor pushState changes or similar?

推荐答案

这是我最终使用自己的.我通过扩展它并用空白方法覆盖方法来制作路由器的模拟版本,以防止它在被调用时调用任何进一步的逻辑:

Here's what I ended up using myself. I made a mock version of the router by extending it and overriding the methods with a blank method to prevent it from invoking any further logic when being called:

describe("routers/main", function() {

    beforeEach(function() {

        // Create a mock version of our router by extending it and only overriding
        // the methods
        var mockRouter = App.Routers["Main"].extend({
            index: function() {},
            login: function() {},
            logoff: function() {}
        });

        // Set up a spy and invoke the router
        this.routeSpy = sinon.spy();
        this.router = new mockRouter;

        // Prevent history.start from throwing error
        try {
            Backbone.history.start({silent:true, pushState:true});
        } catch(e) {

        }

        // Reset URL
        this.router.navigate("tests/SpecRunner.html");
    });

    afterEach(function(){
        // Reset URL
        this.router.navigate("tests/SpecRunner.html");
    });

    it('Has the right amount of routes', function() {
        expect(_.size(this.router.routes)).toEqual(4);
    });

    it('/ -route exists and points to the right method', function () {
        expect(this.router.routes['']).toEqual('index');
    });

    it("Can navigate to /", function() {
        this.router.bind("route:index", this.routeSpy);
        this.router.navigate("", true);
        expect(this.routeSpy.calledOnce).toBeTruthy();
        expect(this.routeSpy.calledWith()).toBeTruthy();
    });

});

请注意,上面使用 sinon.js 来创建 spy,与 underscore.js 一起提供 size 功能.

Note that sinon.js is used above to create the spy, along with underscore.js to provide the size function.

这篇关于正确测试backbone.js中的路由器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:正确测试backbone.js中的路由器?

基础教程推荐