I am currently in the process of writing unit tests for an Angular app, specifically Angular6. One specific component that I am focusing on contains mat-autocomplete functionality. My goal is to ensure that the users are properly filtered based on the input they type in the autocomplete input box. A helpful post that I came across that inspired me can be found here.
Below is a snippet of the code in the spec file:
it('should filter customers', 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;
}
});
}