ViewDestroyedError:尝试使用被破坏的视图:在单元测试 ngOnDestroy

问题描述

我正在对 Angular 组件进行单元测试,它使用了 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:尝试使用被破坏的视图:在 viewDestroyedError 处检测更改

我没有在我的组件中使用任何 ChangeDetectorRef,所以我认为 MatTableDataSource 可能有它,所以我尝试了 this.tableData._renderChangesSubscription.unsubscribe(),但我仍然无法解决问题?有没有人遇到过类似的问题,如果有的话,可以分享一下你的信息吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)