问题
I have the following observables:
public ngAfterViewInit(): void {
fromEvent(this.showFeaturesButton.nativeElement, 'click').pipe(
takeUntil(this.ngUnsubscribe),
withLatestFrom(this.store.pipe(select(fromClientStorage.getSubscription)))
).subscribe(([_event, subscription]) => {
this.featureModal.open(FeatureListComponent, {
data: {
features: subscription.features
},
});
});
}
I am trying to test using:
it('should call modal when feature button is clicked', () => {
const subscription: Subscription = ClientMock.getClient().subscription;
spyOn(instance['store'], 'pipe').and.returnValue(hot('-a', {a: subscription.features}));
spyOn(instance.featureModal, 'open');
instance.ngAfterViewInit();
instance.showFeaturesButton.nativeElement.click();
expect(instance.featureModal.open).toHaveBeenCalledWith(FeatureListComponent, {
data: {
features: subscription.features
}
});
});
However I am never hitting the subscribe which opens the modal. If I remove withLatestFrom
like this:
public ngAfterViewInit(): void {
fromEvent(this.showFeaturesButton.nativeElement, 'click').pipe(
takeUntil(this.ngUnsubscribe)
).subscribe(res) => {
this.featureModal.open(FeatureListComponent, {
data: {
features: res
},
});
});
}
Then subscribe is hit, I am just wondering what I am missing with withLatestFrom
回答1:
it's becase withLatestFrom
create subscription and get value on initiation before spyOn
switchMap
+ combineLatest
fix this problem
public ngAfterViewInit(): void {
fromEvent(this.showFeaturesButton.nativeElement, 'click').pipe(
takeUntil(this.ngUnsubscribe),
switchMap(ev => combineLatest(of(ev), this.store.pipe(select(fromClientStorage.getSubscription))))
).subscribe(([_event, subscription]) => {
this.featureModal.open(FeatureListComponent, {
data: {
features: subscription.features
},
});
});
}
来源:https://stackoverflow.com/questions/52623803/unit-testing-fromevent-observable-with-withlatestfrom