Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test $rootScope.$emit event?

I have below code in abc controller:

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

And the caller function is in xyz controller:

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

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

like image 675
Mithun Shreevatsa Avatar asked Sep 16 '25 12:09

Mithun Shreevatsa


2 Answers

For first controller (abc), where you listen to it using $rootScope.$on, you can first $rootScope.$emit it and $scope.$digest() it. So that you can receive 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 second controller (xyz), You can spy on $rootScope.$emit. And expect it to be called in xyz controller. 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');
    });
});
like image 60
tanmay Avatar answered Sep 18 '25 08:09

tanmay


Using Jasmine, it could 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');
    });
});
like image 45
Mistalis Avatar answered Sep 18 '25 09:09

Mistalis