$ scope。$ on在单元测试

时间:2015-05-29 16:37:43

标签: angularjs unit-testing karma-jasmine

我对我的控制器的初始化部分进行了单元测试,但我似乎无法超过$ scope。$ on是未定义的错误。我想知道在这种情况下如何编写单元测试或如何测试$ scope。$ on()。我没有找到测试这个的官方角度文档。

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'];

我的测试是:

    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);
});

根据我的理解,正确的方法是广播事件而不是窥探$ scope。$ on function本身。

1 个答案:

答案 0 :(得分:2)

问题是 $ broadcast 功能。我写的单元测试没有很好地处理 $ broadcast

我最终做的是这样的事情:

spyOn(scope, '$broadcast').and.callThrough();
rootScope.$broadcast('userDataLoaded', true);