2016-05-31 131 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'); 

}); 
相关问题