How can I test $rootScope.$emit event?

最后都变了- 提交于 2020-01-02 07:05:25

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/43135747/how-can-i-test-rootscope-emit-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!