我试图模拟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 = { …Run Code Online (Sandbox Code Playgroud) 这是一个奇怪的错误。所以我把 jest 更新到 27 然后全部停止工作
导入路径似乎有问题。所以下面的
import { something } form 'src/app/components/.....';
Run Code Online (Sandbox Code Playgroud)
不起作用,但这确实有效:
import { something } from '../../components/....';
Run Code Online (Sandbox Code Playgroud)
我猜这是在 tsconfig 中管理的。这是我的spectsconfig:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jest", // 1
"node",
"Chrome"
],
"esModuleInterop": true, // 2
"emitDecoratorMetadata": true, // 3
"allowSyntheticDefaultImports": true,
},
"files": ["src/test.ts", "src/polyfills.ts"],
"include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}
Run Code Online (Sandbox Code Playgroud)
和主要的 tsconfig:
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true, …Run Code Online (Sandbox Code Playgroud)