单元测试 ngAfterViewInit

Unit testing ngAfterViewInit

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'dataSource': 'undefined'. Current value: '[object Object]'.

在我的 component.ts 中,我遇到了这个错误。由于在 ngafterviewinit 中有代码。

  ngAfterViewInit(): void {
    this.role = this.aut.getuser();
    if (this.role ===  undefined) {
      this.router.navigate(['/']);
    }

    this.ELEMENT_DATA_RED_MALE = this.resul.fetchresults('red', 'male');
    this.dataSourceRedMale = this.ELEMENT_DATA_RED_MALE;
    this.ELEMENT_DATA_RED_FEMALE = this.resul.fetchresults('red', 'female');
    this.dataSourceRedFemale = this.ELEMENT_DATA_RED_FEMALE;
  
    this.ELEMENT_DATA_YELLOW_MALE = this.resul.fetchresults('yellow', 'male');
    this.dataSourceYellowMale = this.ELEMENT_DATA_YELLOW_MALE;
    this.ELEMENT_DATA_YELLOW_FEMALE = this.resul.fetchresults('yellow', 'female');
    this.dataSourceYellowFemale = this.ELEMENT_DATA_YELLOW_FEMALE;
  
    this.ELEMENT_DATA_BLUE_MALE = this.resul.fetchresults('blue', 'male');
    this.dataSourceBlueMale = this.ELEMENT_DATA_BLUE_MALE;
    this.ELEMENT_DATA_BLUE_FEMALE = this.resul.fetchresults('blue', 'female');
    this.dataSourceBlueFemale = this.ELEMENT_DATA_BLUE_FEMALE;
  
    this.ELEMENT_DATA_GREEN_MALE = this.resul.fetchresults('green', 'male');
    this.dataSourceGreenMale = this.ELEMENT_DATA_GREEN_MALE;
    this.ELEMENT_DATA_GREEN_FEMALE = this.resul.fetchresults('green', 'female');
    this.dataSourceGreenFemale = this.ELEMENT_DATA_GREEN_FEMALE;
  }

请指导我测试 ngAfterviewInit,我是 jasmine karma 测试的新手。

我遇到了类似的问题。查看 lifecycle hooks documentation,我将 ngAfterViewInit 更改为 ngAfterContentInit,它起作用了。

参考Link: