我试图模拟 Angular 的PUT
调用HttpClient
以引发错误。我正在使用throwError
它。它不工作。我应该更改什么以使其抛出错误并调用该handleError
方法?我正在使用 Jest。
it(`should call the 'handleError' method when a request to store data was not successful`, () => {
const error: HttpErrorResponse = {
status: 401,
message: 'You are not logged in',
} as HttpErrorResponse;
jest.spyOn(httpClientServiceMock, 'put').mockReturnValue(throwError(error));
const spy = jest.spyOn(httpService, 'handleError');
httpService.requestCall('some-url', ApiMethod.PUT, {});
expect(spy).toBeCalled();
});
服务文件
requestCall(url: string, method: ApiMethod, data?: any): Observable<any> {
const headers = {
'X-XSRF-TOKEN': this.xsrfToken,
'Content-Type': 'application/json; charset=UTF-8',
};
const requestConfig = {
withCredentials: true,
headers,
};
switch (method) {
case ApiMethod.GET:
return this._http.get(url, { withCredentials: true });
case ApiMethod.PUT:
return this._http
.put(url, data, requestConfig)
.pipe(catchError((error) => this.handleError(error)));
}
}
handleError(error: HttpErrorResponse): any {
if (error.error instanceof ErrorEvent) {
console.error(`An error occurred: ${error.error.message}`);
}
return throwError({ error: error.message, status: error.status });
}