Тестирование, если обратный вызов был вызван с использованием $rootScope.$ Broadcast и $scope.$ On

Я пытался проверить, был ли вызван обратный вызов на моем контроллере.

контроллер

(function () {
    'use strict';

    angular
        .module('GeoDashboard')
        .controller('CiudadCtrl', CiudadCtrl);

    CiudadCtrl.$inject = ['$scope', '$interval', '$rootScope','Ciudad'];

    function CiudadCtrl($scope, $interval, $rootScope, Ciudad) {

        $scope.refreshCiudad = refreshCiudad;
        $scope.refreshClima = refreshClima;

        var removeListenerRefreshCiudad = $scope.$on('refreshCiudad', refreshCiudad);
        var cancelIntervalIdClima = $interval(refreshClima, 600000);

        function refreshCiudad() { 
           //...
        }
    }

})();

тестирование

beforeEach(inject(eachSpec));

function eachSpec($rootScope, $controller, $httpBackend, $interval, _Ciudad_){

    rootScope = $rootScope;
    scope = $rootScope.$new();
    httpBackend = $httpBackend;
    interval = sinon.spy($interval);

    CodificacionGeograficaService = _CodificacionGeografica_;
    CiudadService = _Ciudad_;

    CiudadController = $controller('CiudadCtrl', {
       $scope : scope,
       $interval: interval,
       Ciudad: CiudadService
    });  
}

it('3. Debería llamar a "refreshCiudad" al escuchar el evento "refreshCiudad"', spec3);

function spec3(){

    sinon.spy(scope, 'refreshCiudad');

    rootScope.$broadcast('refreshCiudad');

    expect(scope.refreshCiudad).toHaveBeenCalled();
    scope.refreshCiudad.restore();
}

Но когда я пытаюсь передать событие $broadcast, обратный вызов не вызывается.

Что я делаю не так?

1 ответ

Наконец-то это работает, но я не понимаю почему. Решение было обернуть функцию обратного вызова для $scope.$on в другой функции, как это

    function CiudadCtrl($scope, $interval, $rootScope, Ciudad) {

        $scope.refreshCiudad = refreshCiudad;

        //instead this
        //var removeListenerRefreshCiudad = $scope.$on('refreshCiudad', refreshCiudad);
        //I set the callback like this
        var removeListenerRefreshCiudad = $scope.$on('refreshCiudad',  function(){
            $scope.refreshCiudad(); //And this work!
        });

        function refreshCiudad() { 
           //...
        }
    }
Другие вопросы по тегам