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

Mit*_*tsa 3 javascript unit-testing angularjs karma-jasmine

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

   $rootScope.$on('selectedItem', function (event, data) {
       vm.selectedItem = data;
   });
Run Code Online (Sandbox Code Playgroud)

调用函数在xyz控制器中:

  function doThis(){
     $rootScope.$emit('selectedItem', 'somedata');
  }
Run Code Online (Sandbox Code Playgroud)

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

tan*_*may 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');
    });
});
Run Code Online (Sandbox Code Playgroud)

而对于第二个控制器(xyz),你可以spy$rootScope.$emit.而且expect它在被称为xyz控制器.像这样:

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');
    });
});
Run Code Online (Sandbox Code Playgroud)