angular - 为过滤客户的 mat-autocomplete 编写单元测试
问题描述
我正在为 Angular 应用程序编写单元测试,确切地说是 angular6。我在代码中有 mat-autocomplete,我想要测试的只是用户根据我在输入框中输入的内容进行过滤。我受到帖子的启发,请在此处输入链接描述。
这是spec文件的代码片段
it('should filter customer',async () => {
fixture.detectChanges();
let toggleButton = fixture.debugElement.query(By.css('input'));
console.log(toggleButton.nativeElement);
toggleButton.nativeElement.dispatchEvent(new Event('focusin'));
toggleButton.nativeElement.value = "xyz";
toggleButton.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
const matOptions = document.querySelectorAll('mat-option');
expect(matOptions.length).toBe(1); //test fails
})
<mat-form-field >
<input id="inputCustomer" matInput [matAutocomplete]="auto" [formControl]="customerFilterControl">
<mat-autocomplete panelWidth ="450px" #auto="matAutocomplete" [displayWith] = "displayFn" style="width:750px;">
<mat-option *ngFor="let customer of filteredOptions | async" [value] ="customer.AccountID + '('+ customer.AccountName + ')'" (onSelectionChange)="onCustomerChange(customer)">
{{customer.AccountID}} ({{customer.AccountName}})
</mat-option>
</mat-autocomplete>
</mat-form-field>
**typescript.ts**
this.filteredOptions = this.customerFilterControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
_filter(value:any):any[] {
const filterValue = value.toLowerCase();
return this.customers.filter(function (option) {
if(option.AccountID.includes(filterValue) || option.AccountName.includes(filterValue)) {
return option;
}
});
}
解决方案
您似乎缺少初始化选项
it('should filter customer',async () => {
// Prepare the data
const option1 = {AccountID: 1, AccountName: 'AccountName1'};
const option2 = {AccountID: 2, AccountName: 'xyz'}
// Prepare the data source
fixture.component.filteredOptions = of([option1,option2])
fixture.detectChanges();
let toggleButton = let toggleButton = fixture.debugElement.query(By.css('#inputCustomer'));
console.log(toggleButton.nativeElement);
toggleButton.nativeElement.dispatchEvent(new Event('focusin'));
toggleButton.nativeElement.value = "xyz";
toggleButton.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
await fixture.whenStable();
fixture.component._filter("xyz");
fixture.detectChanges();
const matOptions = document.querySelectorAll('mat-option');
expect(matOptions.length).toBe(1); //test fails
})
这样,当您添加自动完成值时,您的组件将有一些值可供选择。
请记住,您应该使用 of 运算符(让我知道它是否有效,因为我没有测试过它)才能使异步管道工作。
推荐阅读
- http - 如何在 Iron 中启用基本授权?
- python - 当一个事件绑定另一个事件时如何停止回调?
- python - 将`add_value_provider_argument`与apache beam io函数一起使用会创建“RuntimeValueProviderError”
- ruby-on-rails - 在单独的表中与 id 和类型的多态关联
- angular - 角度通用窗口未定义
- vim - 如何避免Youcompleteme完成后自动添加头文件
- ruby-on-rails - rails 6 设置 CSP 策略
- excel - 如何设置 Visual Studio 以将 VBA 文件视为纯文本?
- excel - VBA 错误 1004 和源文件变为只读
- javascript - react-redux connect() 函数 mapStateToProps 正在更新,但组件未重新渲染