【问题标题】:Angular 4 testing: how to spy on a service inside host component?Angular 4 测试:如何监视主机组件内的服务?
【发布时间】:2017-10-05 02:06:17
【问题描述】:

我有一个组件,它使用服务来检索数据。它以画廊 ID 作为输入。

export class GalleryComponent implements OnInit {
  private photos: Photo[] = [];
  @Input() private galleryId: number;

  ngOnInit(): void {
    this.galleryService.getPhotos(this.galleryId)
      .subscribe((photos: Photo[]) => this.photos = photos);
  }
}

我正在尝试使用主机组件对其进行测试:

describe('Gallery Component', () => {

  const fakePhotos: Photo[] = [
    {id: 1, photo: 'http://example.com/lena.jpg'} as Photo,
    {id: 2, photo: 'http://example.com/mario.jpg'} as Photo,
  ];

  @Component({
    template: `<gallery [galleryId]="1"></gallery>`
  })
  class TestHostComponent {}

  // ...SKIP CONFIGURATION

  beforeEach(() => {
    fixture = TestBed.createComponent(TestHostComponent);

    const galleryService = fixture.debugElement.injector.get(GalleryService);
    spyOn(galleryService, 'getPhotos').and.returnValue(Observable.of(fakePhotos));

    fixture.detectChanges();
  });

});

但服务的getPhotos 方法永远不会被调用。那么我应该如何正确地窥探子组件的getPhotos 方法呢?

【问题讨论】:

    标签: angular unit-testing


    【解决方案1】:

    我实际上试图监视错误的服务实例。正确的服务应该在我的GalleryComponent 中,而不是在TestHostComponent 中。

    我最终创建了 GalleryService 模拟类:

    class MockService extends GalleryService {
        getPhotos(galleryId: number) {
          return Observable.of(fakePhotos);
        }
    }
    

    并在编译组件之前覆盖组件提供程序:

    beforeEach(async(() => {
        TestBed.overrideComponent(GalleryComponent, {
          set: {providers: [{provide: GalleryService, useClass: MockService}]}
        });
    
        // ...SKIP
    }));
    

    现在我根本不需要监视服务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 2018-12-04
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      • 2017-06-18
      相关资源
      最近更新 更多