2016-03-02 99 views
0

我对测试控制器内的$ emit有点困惑。我正在设置的控制器存在于指令中。我对建立测试的两个部分感到困惑。如何在测试中设置$ emit?我正在使用茉莉花,所以我做了一个

spyON(scope, '$emit') 

我的测试找不到一个对象窥探。这是我的测试。

describe('hero Directive', function() { 
    var $compile, 
     $rootScope, 
     scope, 
     element, 
     ctrl; 

    beforeEach(function() { 
     angular.mock.module('ha.module.core'); 

我定义控制器和设置喷出内部的范围。我编译了html,以便我可以使用该指令。

 angular.mock.inject(function (_$compile_, _$rootScope_, _$controller_) { 
      $compile = _$compile_; 
      $rootScope = _$rootScope_; 
      scope = $rootScope.$new(); 

我认为错误可能是在控制器,但它似乎是树立正确的。

  ctrl = _$controller_('ExploreHeroController', { scope: scope }); 

该指令使用templateUrl我希望我可以用模拟出一个div进行测试并编译它。

  var html = '<div explore-hero></div>'; 
      element = $compile(angular.element(html))(scope); 
      scope.$digest(); 
     }); 

    }); 

    describe('directive controller', function() { 
     it('should dispatch call $emit with $methodsBound', function() { 
      spyOn(scope, '$emit'); 

      //expect(scope.$emit).toHaveBeenCalledWith('$methodsBound'); 
     }); 
    }); 

}); 

信号发送的坐在我的指令控制器的内部

var controller = function($scope) { 
    $scope.$emit('$methodsBound'); 
} 

回答

1

你的指令创建一个孤立的范围,这是调用$放出,所以你需要定义这一个:

var elementScope; 
//beforeEach 
el = angular.element('<your-directive></your-directive>'); 
$compile(el)(scope); 
scope.$digest(); 
elementScope = el.isolateScope(); 

it('should spy isolated scope', function(){ 
     spyOn(elementScope, '$emit'); 
     expect(elementScope.$emit).toHaveBeenCalledWith('$methodsBound'); 
})