首页 > 解决方案 > Angular 7 测试 retryWhen 使用模拟 http 请求无法实际重试

问题描述

refresh_token我有以下拦截器,只要获得任何 401(错误)响应,它就会尝试使用 OAuth 。

基本上在第一个 401 请求上获得了一个刷新令牌,在获得它之后,代码等待 2.5 秒。在大多数情况下,第二个请求不会触发错误,但如果触发(令牌无法刷新或其他),用户将被重定向到登录页面。

export class RefreshAuthenticationInterceptor implements HttpInterceptor {
    constructor(
        private router: Router,
        private tokenService: TokenService,
    ) {}

    public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request)
            .pipe(
                // this catches 401 requests and tries to refresh the auth token and try again.
                retryWhen(errors => {
                    // this subject is returned to retryWhen
                    const subject = new Subject();

                    // didn't know a better way to keep track if this is the first
                    let first = true;

                    errors.subscribe((errorStatus) => {
                        // first time either pass the error through or get new token
                        if (first) {
this.authenticationService.authTokenGet('refresh_token', environment.clientId, environment.clientSecret, this.tokenService.getToken().refresh_token).subscribe((token: OauthAccessToken) => {
                                this.tokenService.save(token);
                            });

                        // second time still error means redirect to login
                        } else {
                            this.router.navigateByUrl('/auth/login')
                                .then(() => subject.complete());

                            return;
                        }

                        // and of course make sure the second time is indeed seen as second time
                        first = false;

                        // trigger retry after 2,5 second to give ample time for token request to succeed
                        setTimeout(() => subject.next(), 2500);
                    });

                    return subject;
                }),
    }
}

问题在于测试。一切正常,除了最后检查路由器是否真的被导航到/auth/login. 不是,所以测试失败。

通过调试,我确定setTimeout回调已执行,但subject.next()似乎没有启动新请求。

我在某处读到,通常retry()在 http 模拟请求上使用 rxjs 时,您应该再次刷新请求。这在下面的代码中被注释掉了,但给出了“无法刷新已取消的请求”。

    it('should catch 401 invalid_grant errors to try to refresh token the first time, redirect to login the second', fakeAsync(inject([HttpClient, HttpTestingController], (http: HttpClient, mock: HttpTestingController) => {
        const oauthAccessToken: OauthAccessToken = {
            // ...
        };
        authenticationService.authTokenGet.and.returnValue(of(oauthAccessToken));
        tokenService.getToken.and.returnValue(oauthAccessToken);

        // first request
        http.get('/api');

        const req = mock.expectOne('/api');
        req.flush({error: 'invalid_grant'}, {
            status: 401,
            statusText: 'Unauthorized'
        });

        expect(authenticationService.authTokenGet).toHaveBeenCalled();

        // second request
        authenticationService.authTokenGet.calls.reset();

        // req.flush({error: 'invalid_grant'}, {
        //    status: 401,
        //    statusText: 'Unauthorized'
        // });

        tick(2500);
        expect(authenticationService.authTokenGet).not.toHaveBeenCalled();
        expect(router.navigateByUrl).toHaveBeenCalledWith('/auth/login');

        mock.verify();
    })));

有谁知道如何修复这个测试?

PS:也欢迎任何关于代码本身的指针:)

标签: angulartestingjasminerxjskarma-jasmine

解决方案


最终我重构了代码以不使用first上面的技巧,这帮助我解决了问题。

对于其他在retryWhen单元测试中苦苦挣扎的人,这是我的最终代码:

拦截器中的代码(简化)

retryWhen((errors: Observable<any>) => errors.pipe(
    flatMap((error, index) => {
        // any other error than 401 with {error: 'invalid_grant'} should be ignored by this retryWhen
        if (!error.status || error.status !== 401 || error.error.error !== 'invalid_grant') {
            return throwError(error);
        }

        if (index === 0) {
            // first time execute refresh token logic...
        } else {
            this.router.navigateByUrl('/auth/login');
        }

        return of(error).pipe(delay(2500));
    }),
    take(2) // first request should refresh token and retry, if there's still an error the second time is the last time and should navigate to login
) ),

单元测试中的代码:

it('should catch 401 invalid_grant errors to try to refresh token the first time, redirect to login the second', fakeAsync(inject([HttpClient, HttpTestingController], (http: HttpClient, mock: HttpTestingController) => {    
    // first request
    http.get('/api').subscribe();

    const req = mock.expectOne('/api');
    req.flush({error: 'invalid_grant'}, {
        status: 401,
        statusText: 'Unauthorized'
    });

    // the expected delay of 2500 after the first retry 
    tick(2500);

    // second request also unauthorized, should lead to redirect to /auth/login
    const req2 = mock.expectOne('/api');
    req2.flush({error: 'invalid_grant'}, {
        status: 401,
        statusText: 'Unauthorized'
    });

    expect(router.navigateByUrl).toHaveBeenCalledWith('/auth/login');

    // somehow the take(2) will have another delay for another request, which is cancelled before it is executed.. maybe someone else would know how to fix this properly.. but I don't really care anymore at this point ;)
    tick(2500);

    const req3 = mock.expectOne('/api');
    expect(req3.cancelled).toBeTruthy();

    mock.verify();
})));

推荐阅读