如何在angular中为Interceptor中的私有函数编写测试用例



这是我的拦截器代码。如何为私有函数handleError400编写测试用例。这个函数我用来在会话到期时注销。我不知道该怎么写。

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

我试过写这样的测试用例,但无法处理Error400函数。因为它显示了一个错误;handleError400"不可分配给类型为"的参数;截距">

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

对此没有直接的答案。尽管如此,还是有一些";破解";就像这个答案一样,测试私有函数一直是一个有争议的话题。

在您的情况下,您可以通过在intercept方法上有多个测试用例来测试私有函数,每个错误代码(例如400401(有一个测试用例,并检查输出是否如预期。

最新更新