【发布时间】: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