[英]Angular Test: Mocking Viewchild projected component and observable property
I have the following code that I can't mock in my unit tests:我有以下无法在单元测试中模拟的代码:
@ContentChild(CarouselInfoComponent) carouselInfo: CarouselInfoComponent;
@ContentChild(CarouselComponent) carousel: CarouselComponent;
ngAfterViewInit(): void {
this.carouselInfo.itemSelected.subscribe((index: number) => {
this.setActiveCarousel(index);
});
this.carousel.itemSelected.subscribe((index: number) => {
this.setActiveCarouselInfo(index);
});
}
I have tried something like this:我试过这样的事情:
// spec
// beforeEach
TestBed.configureTestingModule({
declarations: [ CarouselGalleryComponent, CarouselInfoComponent, CarouselComponent ]
})
// it
spyOn(component.carouselInfo, 'itemSelected').and.returnValue(of(1));
But I get the following error:但我收到以下错误:
Argument of type 'string' is not assignable to parameter of type 'never'
I understand that this is used for methods and basically itemSelected
is a property of the child component (which, by the way, is a component projected using ng-content).我知道这是用于方法,基本上
itemSelected
是子组件的属性(顺便说一下,它是使用 ng-content 投影的组件)。
Note: itemSelected (in both cases) is an instance of EventEmitter en every child component.注意: itemSelected(在这两种情况下)是每个子组件的 EventEmitter 实例。
const myCustomSubject = new Subject();
component.carousel.itemSelected = myCustomSubject.asObservable();
So if you want to simulate a value emit then you can use:所以如果你想模拟一个值发出那么你可以使用:
myCustomSubject.next(1);
You can use ng-mocks
and provide mock properties via MockInstance
.您可以使用
ng-mocks
并通过MockInstance
提供模拟属性。
MockInstance.scope();
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
CarouselGalleryComponent,
MockComponent(CarouselInfoComponent), // <- mock
MockComponent(CarouselComponent), // <- mock
],
});
});
it('test', () => {
MockInstance(CarouselInfoComponent, 'itemSelected', of(1));
MockInstance(CarouselComponent, 'itemSelected', EMPTY);
const fixture = TestBed.createComponent(CarouselGalleryComponent);
fixture.detectChanges();
// now it works.
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.