Angular 4测试:如何监视主机组件内的服务?

时间:2017-10-03 20:19:25

标签: angular unit-testing

我有一个组件,它使用服务来检索数据。它需要图库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方法?

1 个答案:

答案 0 :(得分:0)

我实际上试图窥探错误的服务实例。正确的服务应该在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
}));

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