我创建了一个监听事件并更新其内容的指令:
$rootScope.$on(event, function(e, msg) {
vm.items = msg.data;
});
我想为此创建一个单元测试,我知道如何测试指令是否广播,但我不知道如何测试该指令正在监听。
以下是我如何测试指令是否正在侦听:
describe('input directive', function() {
var ctrl,
$rootScope;
beforeEach(function() {
module('hey.ui');
inject(function($compile, _$rootScope_) {
$rootScope = _$rootScope_;
var elem = $compile('<m-search></m-search>')($rootScope.$new());
$rootScope.$digest();
ctrl = elem.controller('mSearch');
spyOn($rootScope, '$broadcast');
})
});
it('broadcasts e:input-valuechanged on change', function() {
var inputVal = {input: 'input string'};
ctrl.onChange(inputVal);
expect($rootScope.$broadcast).toHaveBeenCalledWith('e:input-valuechanged', {data: inputVal});
});
});
我正在考虑非常愚蠢的测试方法,如下:
describe('list directive', function() {
var ctrl,
$rootScope;
beforeEach(function() {
module('hey.ui');
inject(function($compile, _$rootScope_) {
$rootScope = _$rootScope_;
var elem = $compile('<ecal-list></ecal-list>')($rootScope.$new());
$rootScope.$digest();
ctrl = elem.controller('mList');
spyOn($rootScope, '$broadcast');
})
});
it('should listen to $broadcast', function() {
$rootScope.$broadcast('e:input-valuechanged');
var eventEmitted = false;
$rootScope.$on('e:input-valuechanged', function() {
eventEmitted = true;
console.log(eventEmitted);
});
//run code to test
expect(eventEmitted).toBe(true);
});
});
如何测试指令是否正在侦听特定事件?
答案 0 :(得分:0)
我相信您希望在广播前听取e:input-valuechanged
事件;
it('should listen to $broadcast', function() {
var eventEmitted = false;
$rootScope.$on('e:input-valuechanged', function() {
eventEmitted = true;
console.log(eventEmitted);
});
$rootScope.$broadcast('e:input-valuechanged');
//run code to test
expect(eventEmitted).toBe(true);
});