Правильно ли тестировать роутеры в backbone.js? - PullRequest
31 голосов
/ 09 февраля 2012

Итак, я только начал писать тесты для моего текущего приложения javascript, используя sinon.js & jasmine.js. В целом работает довольно хорошо, но мне также нужно иметь возможность тестировать мои маршрутизаторы.

Маршрутизаторы в своем текущем состоянии будут запускать несколько представлений и прочее, завершая текущий тест jasmine.js, вызывая Backbone.navigate в зависимости от состояния приложения и взаимодействия пользовательского интерфейса.

Так, как я мог проверить, что маршрутизация к различным местоположениям работала бы, поддерживая маршрутизаторы в «песочнице» и не позволяя им изменить маршрут?

Могу ли я установить какую-то фиктивную функцию, которая будет отслеживать изменения pushState или аналогичные?

Ответы [ 6 ]

37 голосов
/ 14 февраля 2012

Вот низкоуровневый способ сделать это с жасмином, протестировав, что pushState работает, как ожидается, и что ваш маршрутизатор настроил все правильно ... Я предполагаю, что router был инициализирован и имеет маршрут home , сопоставленный с ''. Вы можете адаптировать это для других ваших маршрутов. Я также предполагаю, что вы сделали в вашем приложении инициализацию Backbone.history.start({ pushState: true });

    describe('app.Router', function () {

        var router = app.router, pushStateSpy;

        it('has a "home" route', function () {
            expect(router.routes['']).toEqual('home');
        });

        it('triggers the "home" route', function () {
            var home = spyOn(router, 'home').andCallThrough();
            pushStateSpy = spyOn(window.history, 'pushState').andCallFake(function (data, title, url) {
                expect(url).toEqual('/');
                router.home();
            });
            router.navigate('');
            expect(pushStateSpy).toHaveBeenCalled();
            expect(home).toHaveBeenCalled();
            ...
        });
    });  

Вы можете эффективно достичь подобных результатов, выполнив Backbone.history.stop(); по этой причине.

ОБНОВЛЕНИЕ: Браузеры без pushState:

Это, конечно, будет хорошо работать, если ваш браузер, на котором вы тестируете, поддерживает pushState. Если вы тестируете браузеры, которые этого не делают, вы можете выполнить следующие условия:

it('triggers the "home" route', function () {
    var home = spyOn(router, 'home').andCallThrough();

    if (Backbone.history._hasPushState) {
        pushStateSpy = spyOn(window.history, 'pushState').andCallFake(function (data, title, url) {
            expect(url).toEqual('/');
            router.home();
        });
        router.navigate('', {trigger: true});
        expect(pushStateSpy).toHaveBeenCalled();
        expect(home).toHaveBeenCalled();

    } else if (Backbone.history._wantsHashChange) {
        var updateHashSpy = spyOn(Backbone.history, '_updateHash').andCallFake(function (loc, frag) {
            expect(frag).toEqual('');
            router.home();
        });
        router.navigate('', {trigger: true});
        expect(updateHashSpy).toHaveBeenCalled();
        expect(home).toHaveBeenCalled();
    }
});

Если вы используете IE6, удачи.

8 голосов
/ 01 марта 2014

Когда я тестирую магистральный маршрутизатор, меня беспокоит то, что предоставленные мной маршруты вызывают указанные мной функции с правильными аргументами.Многие другие ответы здесь на самом деле не проверяют это.

Если вам нужно проверить функциональность некоторых маршрутов, вы можете протестировать эти функции сами.

Предполагая, что у вас есть простойроутер:

App.Router = Backbone.Router.extend({
  routes: {
    '(/)':'index',
    '/item/:id':'item'
  },
  index: {
    //render some template
  }, 
  item: {
    //render some other template, or redirect, or _whatever_
  }
});

Вот как я это делаю:

describe('Router', function() {

  var trigger = {trigger: true};
  var router

  beforeEach(function() {
    // This is the trick, right here:
    // The Backbone history code dodges our spies
    // unless we set them up exactly like this:
    Backbone.history.stop(); //stop the router
    spyOn(Router.prototype, 'index'); //spy on our routes, and they won't get called
    spyOn(Router.prototype, 'route2'); 

    router = new App.Router(); // Set up the spies _before_ creating the router
    Backbone.history.start();
  });

  it('empty route routes to index', function(){
    Backbone.history.navigate('', trigger);
    expect(router.index).toHaveBeenCalled();
  });

  it('/ routes to index', function(){
    router.navigate('/', trigger);
    expect(router.index).toHaveBeenCalled();
  });

  it('/item routes to item with id', function(){
    router.navigate('/item/someId', trigger);
    expect(router.item).toHaveBeenCalledWith('someId');
  });
});
4 голосов
/ 26 февраля 2012

Вот что я в итоге использовал сам. Я сделал фиктивную версию маршрутизатора, расширив его и заменив методы пустым методом, чтобы он не вызывал дальнейшую логику при вызове:

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 используется выше для создания шпиона, наряду с underscore.js для обеспечения функции size.

2 голосов
/ 13 февраля 2012

Существует очень хороший учебник по тестированию магистрали:

http://tinnedfruit.com/2011/04/26/testing-backbone-apps-with-jasmine-sinon-3.html

1 голос
/ 10 февраля 2012

Вы должны смоделировать Backbone.Router.route, которая является функцией, которая внутренне используется для привязки функций к Backbone.History.

То есть исходная функция:

route : function(route, name, callback) {
  Backbone.history || (Backbone.history = new Backbone.History);
  if (!_.isRegExp(route)) route = this._routeToRegExp(route);
  Backbone.history.route(route, _.bind(function(fragment) {
    var args = this._extractParameters(route, fragment);
    callback.apply(this, args);
    this.trigger.apply(this, ['route:' + name].concat(args));
  }, this));
}

Вы можете сделать что-то вроде этого, просто вызывая функции при инициализации маршрутизатора:

Backbone.Router.route = function(route, name, callback) {
    callback();
}

Вы также можете сохранить обратные вызовы в объекте с маршрутом в качестве имени и вызывать те же шаги шаг за шагом:

var map = {}
Backbone.Router.route = function(route, name, callback) {
    map[route] = callback();
}

for(i in map){
    map[i]();
}
0 голосов
/ 23 сентября 2015

Я начал с использования решения ggozad шпионажа на _updateHash, которое частично мне помогло.Однако я обнаружил, что мои тесты были сбиты с толку, потому что хеш никогда не обновлялся, поэтому код, основанный на вызовах getHash или getFragment, не выполнялся.

В результате я получил следующую вспомогательную функцию, которая подсматриваетна обоих _updateHash и getHash.Первый записывает запрос на обновление хэша, а второй возвращает последний хэш, который был передан _updateHash.Я вызываю эту вспомогательную функцию в своих тестах перед запуском истории Backbone.

    /**
     * Prevent Backbone tests from changing the browser's URL.
     *
     * This function modifies Backbone so that tests can navigate
     * without modifying the browser's URL. It works be adding
     * stub versions of Backbone's hash functions so that updating
     * the hash doesn't change the URL but instead updates a
     * local object. The router's callbacks are still invoked
     * so that to the test it appears that navigation is behaving
     * as expected.
     *
     * Note: it is important that tests don't update the browser's
     * URL because subsequent tests could find themselves in an
     * unexpected navigation state.
     */
    preventBackboneChangingUrl = function() {
        var history = {
            currentFragment: ''
        };

        // Stub out the Backbone router so that the browser doesn't actually navigate
        spyOn(Backbone.history, '_updateHash').andCallFake(function (location, fragment, replace) {
            history.currentFragment = fragment;
        });

        // Stub out getHash so that Backbone thinks that the browser has navigated
        spyOn(Backbone.history, 'getHash').andCallFake(function () {
            return history.currentFragment;
        });
    };
...