具有子组件的父组件的单元测试

时间:2020-03-18 13:19:32

标签: angular unit-testing angular-unit-test

我最近开始学习单元测试,但是我仍然对测试的某些方面感到困惑。

我有一个父组件,其中包含呈现表的 Child 组件。

<section class="header" >
  <h3>Parent Component</h3>
</section>

 <app-mat-table 
   [data]="faculties" 
   [columns]="columns"             <----- Child component
   [countRecords]="length"
   (pageEvent)='pageUpdate($event)'>
</app-mat-table>

</section>
  • 是否需要创建一个模拟Child组件?因为在父组件中,我使用@ViewChild并从 Child 组件中调用方法。
  • 如何测试@Input@Output参数?
  • 如果 Child 方法包含服务中返回的方法怎么办 Observable,我需要监视这项服务吗?

例如:

 getRange(callback) {
    setTimeout(() => this.isLoading = true);
    this.apiService.getRecordsRange(this.entity, this.pageSize, this.pageIndex * this.pageSize)
      .subscribe(data => {
        callback(data);
        this.isLoading = false;
      });
  }

ParentComponent.ts

 export class ParentComponent   {

      @ViewChild(ChildComponent, {static: false}) table: ChildComponent;

      faculties: Faculty[] = [];
      columns: Column [] = [*some Data*];
      length: number;

      pageUpdate() {
        this.table.getRange((data: Faculty[]) => this.faculties = data);
        this.table.getCountRecords(response => this.length = response.numberOfRecords);
      }
}

ChildComponent.html

<div class="table-container">
    <table> 
       <tr *ngFor="let item of data;></tr>  
    </table>
</div>

ChildComponent.ts

export class ChildComponent implements AfterViewInit {

  @Input() data: any[] = [];
  @Input() columns: Column[];
  @Input() countRecords: number;
  @Output() pageEvent = new EventEmitter<PageEvent>();

  constructor(private apiService: ApiService) {}

  ngAfterViewInit(): void {
    this.onPaginationChange({ *emit some stuff* });
  }

   getRange(callback) {
    setTimeout(() => this.isLoading = true);
    this.apiService.getRecordsRange(this.entity, this.pageSize, this.pageIndex * this.pageSize)
      .subscribe(data => {
        callback(data);
        this.isLoading = false;
      });
  }

0 个答案:

没有答案