【发布时间】:2022-01-03 03:08:19
【问题描述】:
我有单元测试用例在角度应用程序中使用输入事件测试全局过滤器功能。我不确定这是否是角度版本问题,或者我是否缺少测试用例中的任何内容。
环境:Angular CLI:12.2.6 节点:14.17.6
这是错误;
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);
}));
我也试过了,还是不行
it('should click Send button with fakeAsync', fakeAsync(() => {
let buttonElement = fixture.debugElement.query(By.css('.globalFilter'));
spyOn(component, 'globalFilter');
//Trigger click event after spyOn
buttonElement.triggerEventHandler('put', null);
tick();
expect(component.globalFilter).toHaveBeenCalled();
}));
错误:
TypeError: Cannot read properties of null (reading 'triggerEventHandler')
如有帮助,不胜感激
【问题讨论】:
-
你把
p-table需要的模块放到TestBed.configureTestingModule的imports数组里了吗?你把所有指令(pTemplate)都放在TestBed.configureTestingModule的declarations数组中了吗? -
不,我没有添加 p-table @AliF50
-
我认为你应该添加它。这就是为什么你无法读取属性
nativeElement的 undefined 因为 Angular 不知道如何渲染p-table及其指令。 -
测试用例看起来不错@AliF50 吗?
-
我认为测试看起来不错,是的。
标签: javascript angular unit-testing karma-jasmine