2015-05-19 109 views
1

我创建了一个监听事件,并更新其内容,像这样一个指令:单元测试angularjs指令收听事件

$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

我相信你想在听广播前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); 
});