【发布时间】:2020-03-21 01:22:41
【问题描述】:
我正在为 Angular 应用程序编写单元测试,确切地说是 angular6。我在代码中有mat-autocomplete,我想要测试的是根据我在输入框中输入的输入过滤的用户。我受到enter link description here 帖子的启发。
这里是spec文件的sn-p代码
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;
}
});
}
【问题讨论】:
-
如果我定义
customers数组,那么你的测试对我有用
标签: angular typescript unit-testing