1

I have unit test case to test global filter function in angular application. I'm not sure if this is an angular version problem or if I'm missing anything from the test case.

Environment : Angular CLI: 12.2.6 Node: 14.17.6

Here's the error;

TypeError: Cannot read properties of null (reading 'nativeElement')

Home.component.ts

  filterGlobal(dt: any, event){
    dt.filterGlobal(event.target.value, 'contains')
  }

Home.component.html

<p-table class="filterTable" #dt [columns]="cols" [value]="cars">
    <ng-template pTemplate="caption">
        <div style="text-align: right">
            <i class="pi pi-search" style="margin:4px 4px 0 0"></i>
            <input type="text" class="globalFilter" pInputText size="50" placeholder="Global Filter" (input)="dt.filterGlobal($event.target.value, 'contains')" style="width:auto">
        </div>
    </ng-template>
    <ng-template pTemplate="header" let-columns>
        <tr>
            <th *ngFor="let col of columns">
                {{col.header}}
            </th>
        </tr>
        <tr>
            <th *ngFor="let col of columns" [ngSwitch]="col.field">
                <input *ngSwitchCase="'brand'" class="brandFilter" pInputText type="text" (input)="dt.filter($event.target.value, col.field, col.filterMatchMode)">
            </th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-rowData let-columns="columns">
        <tr>
            <td *ngFor="let col of columns">
                {{rowData[col.field]}}
            </td>
        </tr>
    </ng-template>
</p-table>

Home.component.spec.ts

it('should use global filter and show 1 items', fakeAsync(() => {
    fixture = TestBed.createComponent(HomeComponent);
    app = fixture.debugElement.componentInstance;
    fixture.detectChanges();

    const globalFilter = fixture.debugElement.query(By.css(".globalFilter"));
    globalFilter.nativeElement.value = "dsad231ff";
    globalFilter.nativeElement.dispatchEvent(new Event("input"));
    tick(300);
    fixture.detectChanges();

    const tableEl = fixture.debugElement.query(By.css(".filterTable"));
    const bodyRows = tableEl.query(By.css('.p-datatable-tbody')).queryAll(By.css('tr'));
    expect(bodyRows.length).toEqual(1);
}));

Appreciated if any help

itgeek
  • 549
  • 1
  • 15
  • 33

0 Answers0