简体   繁体   中英

how to write test case for a private function in Interceptor in angular

This is my interceptor code. How to write test cases for private function handleError400.This function I'm using to logout when session expire. I don't know how write this.

  return next.handle(this.addTokenToRequest(request, this.auth.getAuthorizationToken()))
      .pipe(
        catchError(err => {
          if (err instanceof HttpErrorResponse) {
            switch ((err as HttpErrorResponse).status) {
              case 400:
                return this.handle400Error(err);
              case 401:
                if (request.url.endsWith(constants.endpoints.auth)) {
                  return throwError(err);
                }
                const expiresTime = new Date(localStorage.getItem(constants.localStorage.tokenExpiresTime));
                if (expiresTime.getTime() > new Date().getTime()) {
                  this.logout();
                  return throwError(err);
                }
                return this.handle401Error(request, next);
              default:
                return throwError(err);
            }
          } else {
            return throwError(err);
          }
        }));
  }

  private logout(): void {
    this.router.navigate(['auth/login']);
  }

  private addTokenToRequest(request: HttpRequest<any>, token: string): HttpRequest<any> {
    if (request.headers.get('x-skip-auth-token')) {
      return request.clone({ headers: new HttpHeaders() });
    } else {
      if (request.body instanceof FormData) {
        return request.clone({
          setHeaders: {
            Authorization: token
          }
        });
      } else {
        return request.clone({
          setHeaders: {
            Authorization: token,
            'Content-Type': 'application/json'
          }
        });
      }
    }
  }

  private handle400Error(err: HttpErrorResponse) {
    if (err && err.status === 400 && err.error && err.error.error_message === 'Access token or Refresh token is invalid') {
      return this.logout();
    }
    return throwError(err);
  }

  private handle401Error(request: HttpRequest<any>, next: HttpHandler): any {
    const authResponse = JSON.parse(localStorage.getItem(constants.localStorage.authResponse) || '{}');
    if (authResponse) {
      const promise: Promise<AuthResponseModel> = this.auth.refreshToken(authResponse).toPromise<AuthResponseModel>();
      promise.then(res => {
        if (res) {
          localStorage.setItem(constants.localStorage.tokenExpiresTime, res.expires_in);
          localStorage.setItem(constants.localStorage.authResponse, JSON.stringify(res));
          return next.handle(this.addTokenToRequest(request, res.access_token));
        } else {
          return this.logout() as any;
        }
      });
      promise.catch(() => {
        return this.logout() as any;
      });
    }
  }

I have tried to write test case like this but not able to spyon handleError400 function.Because it showing an error that 'Argument of type '"handleError400"' is not assignable to parameter of type '"intercept"''.

 it('should  call handle400 function ', () => {
    const error = new HttpErrorResponse({
      status: 400,
      statusText: 'ok',
      url: 'url',

    });
    const interceptor: AuthInterceptor = TestBed.inject(AuthInterceptor);
    const handleerrorspy = spyOn(interceptor, 'handleError400').and.returnValue(
      of(error)
    );
    expect(handleerrorspy.calls.any()).toEqual(true);
  });

There're no straightforward answers to this. Although, there're some "hack" like in this answer , testing private function has long been a debatable topic.

In your case you can test the private function by having multiple test cases on the intercept method, one for each error code (eg 400, 401) and check if the output is as expected.

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