0

我想通过.on在我的指令中测试$广播(从控制器)的接收器。在指令预期间谍测试.on得到函数

指令:

describe('<-- myDirective Spec ------>', function() { 

    var scope, $compile, element, $httpBackend, rootScope; 

    beforeEach(angular.mock.module('myApp')); 

    beforeEach(inject(function (_$rootScope_, _$compile_, _$httpBackend_) { 
     scope = _$rootScope_.$new(); 
     $compile = _$compile_; 
     $httpBackend = _$httpBackend_; 
     rootScope = _$rootScope_; 

     var html = '<my-directive></my-directive>'; 
     element = $compile(angular.element(html))(scope); 

     spyOn(scope, '$broadcast').and.callThrough(); 
     scope.$digest(); 
    })); 

    it('should be defined', function() { 
     expect(element).toBeDefined(); 
    }); 

    it('should broadcast ', function() { 
     scope.$broadcast('sendEmail'); 
     expect(scope.$on).toHaveBeenCalledWith('sendEmail', jasmine.any(Function)); 
    }); 
}); 

通过上述,我得到错误:

Expected a spy, but got Function. 
+1

更换

spyOn(scope, '$broadcast').and.callThrough(); 

您是在'$范围从事间谍活动。$ broadcast',不'$ on'。 – Lee

回答

1

更新:

您可以测试简单,如果你的$广播获取调用与

expect(scope.$broadcast).toHaveBeenCalled() 

或实际测试$上做类似

scope.$on('sendEmail', spyFunction) 
expect(spyFunction).toHaveBeenCalledWith('sendEmail') 

原因:$广播实际上并不在函数调用$。 $ on是一个侦听器,它在侦听事件(第一个参数)时调用回调函数(作为第二个参数传递)。


您目前正在监听范围的$ broadcast函数,并且已经在函数上对$进行了测试。您需要通过

spyOn(scope, '$on').and.callThrough(); 
+0

厌倦了这一点,请参阅错误:期待的间谍$已被['sendEmail',]调用,但它从未被调用过。 –

+1

这是一个不同的问题。这意味着你的测试失败了,即$ on没有被调用,reason:它从来没有真正被调用过,它是你传递的第二个参数getback的第一个参数作为参数传递的回调函数。 – yoogeeks