Angular Component UI单元测试的隔离策略

时间:2022-07-26
本文章向大家介绍Angular Component UI单元测试的隔离策略,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

这是我需要进行单元测试的Component UI:

可以看到它依赖了另一个Component,其selector为cx-carousel.

因此我在单元测试实现文件里,给它创建一个mock Component:MockCarouselComponent:

@Component({
  selector: 'cx-carousel',
  template: `
    <ng-container *ngFor="let item$ of items">
      <ng-container
        *ngTemplateOutlet="template; context: { item: item$ | async }"
      ></ng-container>
    </ng-container>
  `,
})
class MockCarouselComponent {
  @Input() title: string;
  @Input() template: TemplateRef<any>;
  @Input() items: any[];
}

可以看到,MockComponent和生产版本的Component,属性类型和名称完全一致:

mock的carousel title数据:

生产代码里,carousel template里显示的属性有name和price:

为这两个属性提供的mock数据:

最后生成的mock UI: