vendredi 29 mai 2015

$scope.$on is undefined in unit test

I'm unit testing the initialization part of my controller and I can't seem to get over $scope.$on is undefined error. I would like to know how to write the unit test in this case or how to test $scope.$on(). I have failed to find the official angular documentation for testing this.

var SidebarController = function ($rootScope, $scope, $window, $location, PersonService, SearchService) {
    $scope.navName = 'Filters'
    $scope.currentFilter = null;
    $scope.filterResult = null;
    $scope.showFilters = true;
    $rootScope.subTabs = null;

    $scope.$on('userDataLoaded', function () {
        //doing stuff here
    });
    //... more stuff here
}

SidebarController.$inject = ['$rootScope', '$scope', '$window', '$location', 'PersonService', 'SearchService'];

and my test is:

    beforeEach(inject(function (_$controller_, _$rootScope_, _$window_, _$location_, _$httpBackend_, _PersonService_, _SearchService_) {
    $controller = _$controller_;
    scope = _$rootScope_.$new();
    rootScope = _$rootScope_;
    location = _$location_;
    $httpBackend = _$httpBackend_;
    mockWindow = _$window_;
    mockPersonService = _PersonService_;
    mockSearchService = _SearchService_;
    rootScope.userInfo = { tabs: [] };
    scope.$on = function (event, callback) { };
    scope.$digest();
}));

afterEach(function () {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
});

it('should set  the initial data', function () {
    $controller('SidebarController', { $rootScope: rootScope, $scope: scope, PersonService: mockPersonService });

    rootScope.$broadcast('userDataLoaded');

    expect(scope).toBeDefined();
    expect(scope.navName).toEqual('Filters');
    expect(scope.currentFilter).toBe(null);
    expect(scope.filterResult).toBe(null);
    expect(scope.showFilters).toBe(true);
    expect(rootScope.subTabs).toBe(null);
});

From what I understand the correct way to do it is to broadcast the event and not spyOn the $scope.$on function itself.

Aucun commentaire:

Enregistrer un commentaire