Angular12 PrimeNG表格全局过滤单元测试报nativeElement空错误求助
问题原因
报错是因为fixture.debugElement.query(By.css(".globalFilter"))返回了null,测试环境没有找到对应的全局过滤输入框,调用nativeElement属性时就触发了空指针错误。
解决步骤
- 补全测试模块的依赖导入
测试环境不会自动导入业务代码用到的PrimeNG组件,需要在TestBed配置中手动添加用到的依赖:
import { TableModule } from 'primeng/table'; import { InputTextModule } from 'primeng/inputtext'; // 测试模块配置 TestBed.configureTestingModule({ imports: [TableModule, InputTextModule], declarations: [HomeComponent] })
- 初始化组件依赖的变量
p-table绑定了cols和cars两个变量,测试时如果这两个变量为空,p-table不会渲染caption模板和内部的输入框,需要在第一次变更检测前赋值模拟数据:
fixture = TestBed.createComponent(HomeComponent); app = fixture.debugElement.componentInstance; // 赋值模拟的列配置和表格数据 app.cols = [ { field: 'brand', header: '品牌', filterMatchMode: 'contains' }, // 补充其他你实际用到的列配置 ]; app.cars = [ { brand: 'dsad231ff' }, { brand: '其他测试数据' } ]; fixture.detectChanges(); // 赋值完成后再执行变更检测
- 兼容模板渲染延迟
PrimeNG组件的模板渲染可能存在微小延迟,可在变更检测后加短时间等待,同时先校验元素是否存在,避免空指针:
fixture.detectChanges(); tick(100); // 等待模板渲染完成 const globalFilter = fixture.debugElement.query(By.css(".globalFilter")); expect(globalFilter).toBeTruthy(); // 先校验元素存在
- 修正tbody选择器兼容问题
部分PrimeNG 12版本的表格tbody类为.p-datatable-data,如果获取表格行时报空,可替换选择器做兼容:
const bodyRows = tableEl.query(By.css('.p-datatable-tbody, .p-datatable-data')).queryAll(By.css('tr'));
修改后完整测试用例参考
it('should use global filter and show 1 items', fakeAsync(() => { fixture = TestBed.createComponent(HomeComponent); app = fixture.debugElement.componentInstance; // 初始化模拟数据 app.cols = [{ field: 'brand', header: '品牌', filterMatchMode: 'contains' }]; app.cars = [{ brand: 'dsad231ff' }, { brand: 'test' }]; fixture.detectChanges(); tick(100); const globalFilter = fixture.debugElement.query(By.css(".globalFilter")); expect(globalFilter).toBeTruthy(); globalFilter.nativeElement.value = "dsad231ff"; globalFilter.nativeElement.dispatchEvent(new Event("input")); tick(); fixture.detectChanges(); const tableEl = fixture.debugElement.query(By.css(".filterTable")); expect(tableEl).toBeTruthy(); const bodyRows = tableEl.query(By.css('.p-datatable-tbody')).queryAll(By.css('tr')); expect(bodyRows.length).toEqual(1); }));
内容的提问来源于stack exchange,提问作者itgeek
相关产品推荐
相关产品推荐

