As I work on writing unit tests for an HTML div with a condition using *ngIf, I come across a specific scenario.
<div *ngIf="clientSearchResults$ | async as searchResults" class = 'fgf' #datalist id="mydata" >
<app-client-list id="clientDataTable1" class="clientDataTable dataTable" [clients]='searchResults'></app-client-list>
</div>
The *ngIf condition becomes true when data is received from the ngrx store, as explained in the component code snippet below.
searchData(client: Client) {
//// some conditions
this._clientService.getClientList()
.subscribe(data => {
const filteredData = this.filterData(data, client);
this.isDataFound = filteredData !== null && filteredData.length > 0;
this.testbool = true;
/// The div element is filled with data using the async condition here.
this.store.dispatch(new SetClientSearchResultsAction(filteredData));
});
}
When writing the unit test case for this scenario, I encountered an issue.
it('should search the data with valid client passed from UI', async(() => {
let debugFixture: DebugElement = fixture.debugElement;
let htmlElement: HTMLElement = debugFixture.nativeElement;
let clientListGrid = htmlElement.getElementsByClassName('fgf');
let testbool= htmlElement.getElementsByClassName('testbool');
spyOn(component, 'searchData').and.callThrough();
spyOn(component, 'filterData').and.returnValue(CLIENT_OBJECT);
spyOn(clientService, 'getClientList').and.callThrough();
console.log("=========before======="+ clientListGrid.length);
component.searchData(validClient);
component.clientSearchResults$ = store.select('searchResults');
fixture.detectChanges();
debugFixture = fixture.debugElement;
htmlElement = debugFixture.nativeElement;
clientListGrid = htmlElement.getElementsByClassName('fgf');
console.log("=========after ======="+ clientListGrid.length);
expect(component.searchData).toHaveBeenCalled();
}));
The issue lies in the fact that the console logs a length of 0 both before and after calling the function, when it should be 1 after receiving data from the store. This discrepancy is attributed to the *ngIf condition,
*ngIf="clientSearchResults$ | async as searchResults"
.
Even though data loads into the div, I struggle with testing this aspect in the unit test. Any suggestions on how to tackle this?