gpt4 book ai didi

angularjs - 如何为单元测试的 Angular ui-select 指令触发更改事件?

转载 作者:行者123 更新时间:2023-12-02 03:10:51 24 4
gpt4 key购买 nike

我想测试使用 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>

问题是:当对使用此指令的代码进行单元测试时,如何触发此控件上的更改事件?

最佳答案

我也有同样的挫败感。我在 ui-select spec 中找到执行 on-select 函数需要在单击其中一个选项后调用 $timeout.flush()

像这样(不要忘记注入(inject) $timeout):

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');

});

关于angularjs - 如何为单元测试的 Angular ui-select 指令触发更改事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37553270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com