2016-05-31 100 views
3

我想測試我的代碼,使用的用戶界面,選擇指令:如何觸發單元測試的角度ui-select指令的更改事件?

<ui-select class="firstSelect" 
     ng-model="singleFilter.selectedField" 
     ng-disabled="vm.filterDisabled" 
     on-select="vm.itemSelected(singleFilter)"      
     theme="bootstrap"> 
     <ui-select-match placeholder="..."> 
       {{$select.selected.name}}</ui-select-match> 
     <ui-select-choices repeat="field in singleFilter.fields | filter: $select.search"> 
        <span ng-bind-html="field.name | highlight: $select.search"></span> 
     </ui-select-choices> 
</ui-select> 

的問題是:我怎麼能觸發這一控制權發生變化時,當單元測試我的代碼,使用此指令?

回答

0

你的單元測試應該直接調用itemSelected函數。所以一旦你在單元測試中創建一個控制器的實例,只需調用:

vm.itemSelected(mockData); 
+1

測試的相關部分,我已經做到這一點。但是我想知道on-select接線是否正確。 – rogergl

0

我也有同樣的挫敗感。我在ui-select spec中發現執行on-select函數需要在點擊其中一個選項後調用$timeout.flush()

像這樣的東西(不要忘記注入$超時):

compiledUiSelectEl.find('.ui-select-choices-row-inner')[0].click(); 
scope.$digest(); 
$timeout.flush(); 

而且包括ui-select spec

function compileTemplate(template) { 
    var el = $compile(angular.element(template))(scope); 
    scope.$digest(); 
    return el; 
} 

function clickItem(el, text) { 

    if (!isDropdownOpened(el)) { 
    openDropdown(el); 
    } 

    $(el).find('.ui-select-choices-row div:contains("' + text + '")').click(); 
    scope.$digest(); 
} 


it('should invoke select callback on select', function() { 

    scope.onSelectFn = function ($item, $model, $label) { 
    scope.$item = $item; 
    scope.$model = $model; 
    }; 
    var el = compileTemplate(
    '<ui-select on-select="onSelectFn($item, $model)" ng-model="selection.selected"> \ 
     <ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \ 
     <ui-select-choices repeat="person.name as person in people | filter: $select.search"> \ 
     <div ng-bind-html="person.name | highlight: $select.search"></div> \ 
     <div ng-bind-html="person.email | highlight: $select.search"></div> \ 
     </ui-select-choices> \ 
    </ui-select>' 
); 

    expect(scope.$item).toBeFalsy(); 
    expect(scope.$model).toBeFalsy(); 

    clickItem(el, 'Samantha'); 
    $timeout.flush(); 


    expect(scope.selection.selected).toBe('Samantha'); 

    expect(scope.$item).toEqual(scope.people[5]); 
    expect(scope.$model).toEqual('Samantha'); 

}); 
相關問題