我正在为angular应用程序编写单元测试,准确地说就是angular6。我在代码中有mat-autocomplete,所有我想测试的是根据我在输入框中输入的输入过滤的用户。我受到了enter link description here这篇文章的启发。
以下是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;
}
});
}

发布于 2019-11-26 01:30:17
你似乎错过了初始化你的选项
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操作符(让我知道它是否工作,因为我还没有测试过它),以使异步管道工作。
https://stackoverflow.com/questions/59037128
复制相似问题