gpt4 book ai didi

angular - 使用 Marbles 对外部 URL 进行单元测试 NGRX 效果

转载 作者:太空狗 更新时间:2023-10-29 17:38:42 25 4
gpt4 key购买 nike

当触发效果时,我想在单元测试中测试两个可观察对象,以获得这部分代码的 100% 代码覆盖率。因为 window.location.href 被触发,我无法正确测试它。

export class RouteHelper {
static redirectToExternalUrl(url: string): any {
window.location.href = url;
}
}

效果

@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']],
}),
);
}
}),
);

测试 else 条件

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);
});

测试不适用于 if 条件

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);
});

谁能解释一下如何测试 If 条件?

最佳答案

解决方法:

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();
});

关于angular - 使用 Marbles 对外部 URL 进行单元测试 NGRX 效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56115132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com