angular - ViewDestroyedError:尝试使用已破坏的视图:在对 ngOnDestroy 进行单元测试时发生 viewDestroyedError 的检测变化
问题描述
我正在对 Angular 组件进行单元测试,该组件使用角度材料的 MatTableDataSource。为了使用 mat-table 的分页器,我不得不在 ngAfterViewInit 中添加以下内容。
export class TestComponent implements OnInit, OnDestroy, AfterViewInit {
@ViewChild('paginator', { read: MatPaginator }) paginator: MatPaginator;
private subscription: Subscription;
tableData = new MatTableDataSource();
constructor(private readonly dataService: DataService) {}
ngOnInit() {
this.subscription = this.dataService.getData().subscribe(data => {
console.log(data);
});
}
ngAfterViewInit() {
if(this.tableData) {
this.tableData.paginator = this.paginator;
}
}
ngOnDestroy() {
if(this.subscription) {
this.subscription.unsubscribe();
}
}
}
当我对 ngDestroy 进行单元测试时,就会出现问题。
it('should unscribe', () => {
component.subscription = new Subscription();
component.ngOnDestroy();
expect(component.subscription.closed).toBe(true);
})
因此,它返回以下错误,错误:ViewDestroyedError: Attempt to use a destroyed view: detectChanges at viewDestroyedError
我的组件中没有使用任何 ChangeDetectorRef,所以我认为 MatTableDataSource 可能有它,所以我尝试了 this.tableData._renderChangesSubscription.unsubscribe(),但仍然无法解决问题?有没有人遇到过类似的问题,如果有,可以分享一下你的信息吗?
解决方案
推荐阅读
- android - 可点击 RecyclerView 中的项目
- python - 从 json 中删除重复项
- asp.net - 为每个用户使用相同的会话 ID?
- c++ - AVX2 - 方法比经典版本慢 14 倍
- ionic-framework - livereload 不提供地址选择
- c++ - 我应该如何在文本 RPG 中调用玩家咒语?
- python - Python 代码不工作:TypeError,'int' object is not callable
- php - 我可以在不重复自己的情况下执行 SELECT 查询吗?
- python - 刽子手游戏,但我在使用列表功能时遇到问题
- powershell - 如何防止(序列化)表达式展开