【问题标题】:Unit Test NGRX effect with Marbles for an external URL使用 Marbles 对外部 URL 进行单元测试 NGRX 效果
【发布时间】:2023-03-13 00:32:02
【问题描述】:

当一个效果被触发时,我想在单元测试中测试这两个 observables,以获得这部分代码的 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']],
                }),
            );
        }
    }),
);

测试其他条件的工作

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 条件吗?

【问题讨论】:

    标签: angular ngrx ngrx-effects jasmine-marbles


    【解决方案1】:

    解决方案:

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

    【讨论】:

      【解决方案2】:

      您可以使RouteHelper 可注入并在测试期间提供模拟实现。这样您就可以验证该方法是否已被调用。

      【讨论】:

        猜你喜欢
        • 2018-01-04
        • 2018-05-15
        • 2019-01-14
        • 1970-01-01
        • 2019-02-06
        • 1970-01-01
        • 2019-06-23
        • 2021-06-26
        • 2019-04-20
        相关资源
        最近更新 更多