Pri*_*hra 5 observable rxjs jestjs angular angular-jest
我试图模拟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();
});
Run Code Online (Sandbox Code Playgroud)
服务文件
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 });
}
Run Code Online (Sandbox Code Playgroud)
你非常接近!
您必须订阅从httpService.requestCall('some-url', ApiMethod.PUT, {})函数返回的observable。由于这是异步的,因此需要进行其他更改
const { of , throwError, operators: {
catchError
}
} = rxjs;
const httpClientServiceMock = {
put: () => of ({
value: 'test'
})
};
const httpService = {
requestCall(url, data, requestConfig) {
return httpClientServiceMock
.put(url, data, requestConfig)
.pipe(catchError((error) => this.handleError(error)));
},
handleError(error) {
return throwError({});
}
};
const ApiMethod = {
PUT: ''
}
const {
expect,
test,
run,
it,
describe,
jest
} = jestLite.core;
describe('httpService', () => {
it(`should call the 'handleError' method when a request to store data was not successful`, done => {
const error = {
status: 401,
message: 'You are not logged in',
}
jest.spyOn(httpClientServiceMock, 'put').mockReturnValue(throwError(error));
const spy = jest.spyOn(httpService, 'handleError');
httpService
.requestCall('some-url', ApiMethod.PUT, {})
.subscribe(pr => {
done.fail(new Error(`It shouldn't go this path!`))
}, error => {
expect(spy).toBeCalled();
done();
});
});
});
run().then(result => {
console.log(result[0]);
})Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/npm/jest-lite@1.0.0-alpha.4/dist/core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3832 次 |
| 最近记录: |