2015-05-19 78 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); 
});