简体   繁体   中英

angular 7: how to unit test retries on an http interceptor

I've got an HTTP interceptor that is used for adding headers (authentication) and for performing logging when an error happens. Currently, it uses a custom retry strategy which will try to call the web service 3 times before generating an error. Here's the code that is used in the intercept method:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const headers = this.obtemHeaders();
    const requestClonado = req.clone({ headers });
    return next.handle(requestClonado).pipe(
                    retryWhen(this.retryStrategy()),
                    catchError(err => {
                        console.error(err);
                        let msgErro: string;
                        if(err instanceof HttpErrorResponse && this._servicoAutenticacao.trataErroFimSessao(err)) {
                            msgErro = "A sua sessão terminou. Vai ser redirecionado para a página de login" ;
                        }
                        else if(err.status === 503 ) {
                            msgErro = "O servidor não devolveu uma resposta válida (503).";
                        }
                        else {
                            msgErro = err.error && err.error.message ? err.error.message : "Ocorreu um erro no servidor.";
                        }
                        if(err.status !== 503) {
                            this._logger.adicionaInfoExcecao(msgErro).subscribe();
                        }
                        return throwError(msgErro);
                    }
                ));
}

What's the best approach for unit testing the retry attempts? I've tried writing something like this:

it("deve efetuar retry e chamar logging antes redirecionar", fakeAsync((done) => {
    httpClient.get("/error").subscribe( _ => {},
        err => {
            expect(err).toBeTruthy();
            done();
            } );
    const request = httpMock.expectOne("/error");
    request.error(new ErrorEvent(errorMsg));
    tick(500);
    tick(500);
    tick(500);

    expect(trataFimSessaoSpy).toHaveBeenCalled();
    expect(trataLogging).toHaveBeenCalledWith({msg: errorMsg});
});

Unfortunately, it doesn't work. Can anyone help and point me in the right direction?

thanks

Ok, it seems like lunch has helped me solve this:

it("deve efetuar retry 3xs e chamar logging antes redirecionar com erro 500", fakeAsync(() => {
    httpClient.get("/error").subscribe( _ => {},
                                        err => {
                                            expect(err).toBeTruthy();
                                            expect(trataFimSessaoSpy).toHaveBeenCalled();
                                            expect(trataLogging).toHaveBeenCalledWith({msg: errorMsg});
                                        });
    let request: TestRequest;
    for(let i = 0; i < 3; i++) {
        request = httpMock.expectOne("/error");
        request.flush( {message: errorMsg}, { status: 500, statusText: "Server error"} );
        tick(500);
    }
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM