如何对需要测试其发射的angular指令进行茉莉花单元测试?
这个指令是一个属性指令,在我需要测试的指令中有一个emit。
最好这样做吗?
这是我目前的测试:
//broadcast test:
describe('broadcast called', function() {
var rootScope, testService;
beforeEach(inject(function(_$rootScope_, $injector) {
rootScope = _$rootScope_;
testService = $injector.get('testFactory');
spyOn(rootScope, "broadcast");
}));
it('should be broadcast', function() {
testService.emitTest();
expect(rootScope.broadcast).toHaveBeenCalledWith('test1');
});
});
当前代码:
appservicemod.factory('testFactory', ['$rootScope', function ($rootScope) {
var emitTest = function(){
$rootScope.$broadcast('test1');
}
return {
emitTest: emitTest
}
}
]);
答案 0 :(得分:1)
间谍
spyOn(scope, 'emit');
并且在测试中验证它被称为
expect(scope.emit).toHaveBeenCalledWith('valueItShouldBeCalledWith');
答案 1 :(得分:1)
除了一些问题外,您当前的方法似乎运行良好:
$broadcast
,而不是broadcast
无处不在beforeEach(module('app'))
如果您解决了这些问题,则可以:http://jsfiddle.net/MMiszy/c4fz58sp/1/
describe('broadcast called', function() {
var $rootScope, testService;
beforeEach(module('app'));
beforeEach(inject(function(_$rootScope_, $injector) {
$rootScope = _$rootScope_;
spyOn($rootScope, "$broadcast");
testService = $injector.get('testFactory');
}));
it('should broadcast', function() {
testService.emitTest();
expect($rootScope.$broadcast).toHaveBeenCalledWith('test1');
});
});