How can I check $ rootScope. $ Emit event?

I have some code in my controller abc

:

   $rootScope.$on('selectedItem', function (event, data) {
       vm.selectedItem = data;
   });

      

And the caller function is in the controller xyz

:

  function doThis(){
     $rootScope.$emit('selectedItem', 'somedata');
  }

      

How can I reproduce or ridicule this scenario in karma test?

+3


source to share


2 answers


For the first controller ( abc

) where you listen to it with $rootScope.$on

, you can first have $rootScope.$emit

it and $scope.$digest()

it. So you can get it in $on

.

var rootScope;
beforeEach(inject(function(_$rootScope_) {
    rootScope = _$rootScope_;
}));

describe("some function", function() {
    it("should receive selectedItem with $on", function() {
        rootScope.$emit('selectedItem', 'somedata');
        $scope.$digest();
        expect(vm.selectedItem).toEqual('somedata');
    });
});

      



And for the second controller ( xyz

) you can spy

on $rootScope.$emit

. And expect

it should be called in the controller xyz

. Like this:

var rootScope;
beforeEach(inject(function(_$rootScope_) {
    rootScope = _$rootScope_;
    spyOn(rootScope, '$emit');
}));

describe("doThis function", function() {
    it("should $emit selectedItem", function() {
        vm.doThis(); // or if you use $scope, call it that way
        expect(rootScope.$emit).toHaveBeenCalledWith('selectedItem');
    });
});

      

+5


source


Using jasmine, it can look like this:



var rootScope;
beforeEach(inject(function($injector) {
    rootScope = $injector.get('$rootScope');
    spyOn(rootScope, '$emit');
}));

describe("$rootScope event testing", function() {
    it("should $emit selectedItem", function() {
        expect(rootScope.$emit).toHaveBeenCalledWith('selectedItem');
    });
});

      

+2


source







All Articles