我是Angular的新手,我正在尝试使用Angular 5构建一个具有自动完成功能的文本字段 .
我在Angular Material docs中找到了这个例子:
https://stackblitz.com/angular/kopqvokeddbq?file=app%2Fautocomplete-overview-example.ts
我想知道如何编写单元测试来测试自动完成功能 . 我正在为input元素设置一个值并触发'input'事件并尝试选择mat-option元素,但是看到它们都没有创建:
我的组件html的相关部分:
<form>
<mat-form-field class="input-with-icon">
<div>
<i ngClass="jf jf-search jf-lg md-primary icon"></i>
<input #nameInput matInput class="input-field-with-icon" placeholder="Type name here"
type="search" [matAutocomplete]="auto" [formControl]="userFormControl" [value]="inputField">
</div>
</mat-form-field>
</form>
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.name"
(onSelectionChange)="onNameSelect(option)">
{{ option.name }}
</mat-option>
</mat-autocomplete>
规格文件:
it('should filter users based on input', fakeAsync(() => {
const hostElement = fixture.nativeElement;
sendInput('john').then(() => {
fixture.detectChanges();
expect(fixture.nativeElement.querySelectorAll('mat-option').length).toBe(1);
expect(hostElement.textContent).toContain('John Rambo');
});
}));
function sendInput(text: string) {
let inputElement: HTMLInputElement;
inputElement = fixture.nativeElement.querySelector('input');
inputElement.focus();
inputElement.value = text;
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
return fixture.whenStable();
}
组件html:
userFormControl: FormControl = new FormControl();
ngOnInit() {
this.filteredOptions = this.userFormControl.valueChanges
.pipe(
startWith(''),
map(val => this.filter(val))
);
}
filter(val: string): User[] {
if (val.length >= 3) {
console.log(' in filter');
return this.users.filter(user =>
user.name.toLowerCase().includes(val.toLowerCase()));
}
}
在此之前,我意识到为了使FormControl对象设置值,我必须首先执行inputElement.focus(),这与使用角度材质的mat输入有关 . 是否有什么东西要触发打开mat-options窗格?
如何使此测试工作?
1 回答
您需要添加更多活动 . 我和你一样或多或少都有同样的问题,它只在我触发focusin事件时起作用 .
我在我的代码中使用这些事件 . 不确定是否需要全部 .
inputElement.dispatchEvent(new Event('focus')); inputElement.dispatchEvent(new Event('focusin')); inputElement.dispatchEvent(new Event('input')); inputElement.dispatchEvent(new Event('keydown'));
你需要将它添加到你的sendInput函数......