首页 > 解决方案 > 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(),但仍然无法解决问题?有没有人遇到过类似的问题,如果有,可以分享一下你的信息吗?

标签: angulartypescriptunit-testingmat-tablengondestroy

解决方案


推荐阅读