angularjs - $scope.$on is undefined in unit test -
i'm unit testing initialization part of controller , can't seem on $scope.$on undefined error. know how write unit test in case or how test $scope.$on(). have failed find official angular documentation 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 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 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 understand correct way broadcast event , not spyon $scope.$on function itself.
the issue $broadcast functionality. unit test wrote did not handle $broadcast well.
what did this:
spyon(scope, '$broadcast').and.callthrough(); rootscope.$broadcast('userdataloaded', true);
Comments
Post a Comment