When an effect is triggered, i would like to test both observables in unit test, to get a 100% code coverage for this part of code. because a window.location.href
is triggered, I can't test it correctly.
export class RouteHelper {
static redirectToExternalUrl(url: string): any {
window.location.href = url;
}
}
Effect
@Effect()
handleCreatePaymentSuccess$: Observable<
{} | routerActions.Go
> = this.actions$.pipe(
ofType(cartConfigActions.CREATE_PAYMENT_SUCCESS),
switchMap((action: any) => {
if (action.payload.redirect) {
/* istanbul ignore next */
return Observable.create(
RouteHelper.redirectToExternalUrl(action.payload.redirect),
);
} else {
return of(
new routerActions.Go({
path: [RouteHelper.paths['validate']],
}),
);
}
}),
);
Test working for the else condition
it('should dispatch router action Go on success if no redirect url is provided', () => {
const payload = { redirect: null };
const action = new fromCartConfig.CreatePaymentSuccess(payload);
const completion = new routeractions.Go({
path: [RouteHelper.paths['validate']],
});
actions$.stream = cold('-a', { a: action });
const expected = cold('-c', { c: completion });
expect(effects.handleCreatePaymentSuccess$).toBeObservable(expected);
});
Test not working for the if condition
it('should redirect to url that is returned from api', () => {
const payload = { redirect: 'http://www.stackoverflow.com' };
spyOn(RouteHelper, 'redirectToExternalUrl').withArgs(payload.redirect);
const action = new fromCartConfig.CreatePaymentSuccess(payload);
const completion = Observable.create(RouteHelper.redirectToExternalUrl);
actions$.stream = cold('-a', { a: action });
const expected = cold('-c', { c: completion });
expect(effects.handleCreatePaymentSuccess$).toBeObservable(expected);
});
Can someone explain how to test the If condition?
Solution:
it('should dispatch router action Go on success if redirect url is provided', () => {
spyOn(RouteHelper, 'redirectToExternalUrl').and.callFake(() => {});
const payload = { redirect: 'www.buckaroo.nl' };
const action = new fromCartConfig.CreatePaymentSuccess(payload);
actions$.stream = cold('-a', { a: action });
const expected = cold('');
expect(effects.handleCreatePaymentSuccess$).toBeObservable(expected);
expect(RouteHelper.redirectToExternalUrl).toHaveBeenCalled();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With