我怎样才能测试$ rootScope。$ emit事件?

时间:2017-03-31 08:14:19

标签: javascript angularjs unit-testing karma-jasmine

我在abc控制器中有以下代码:

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

调用者函数位于xyz控制器:

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

如何在业力测试中复制或模仿这种情况?

2 个答案:

答案 0 :(得分:5)

对于使用abc收听的第一个控制器($rootScope.$on),您可以先$rootScope.$emit$scope.$digest()它。这样您就可以在$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');
    });
});

对于第二个控制器(xyz),您可以在spy$rootScope.$emit。并expectxyz控制器中调用它。像这样:

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

答案 1 :(得分:2)

使用Jasmine,它看起来像这样:

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