总结问题:
我想用 Spectator 和 Jest 测试我的自定义 ErrorHandler。我希望通过一个简单的测试,其中一个特定的方法handleFailFastError
被调用一次以获取HttpErrorResponse
状态代码500
。实际结果是在另一个方法中HttpErrorResponse
被处理。TypeError
描述您尝试过的内容:
我检查了我是否在方法内,是的,我在。检查console.log
电话并打印出错误。它是一个{castToWriteable: [Function]}
对象。因此,我检查它是否是一个实例的HttpErrorResponse
条件失败了,并且我的 handleError 将响应作为 TypeError 处理。在这个例子上定位我自己。还检查了这个stackoverflow条目。
显示一些代码 ErrorHandler:
@Injectable()
export class ErrorHandlerInterceptor implements ErrorHandler, OnDestroy {
private _destroy$ = new Subject();
constructor(
private _injector: Injector
) {
}
public ngOnDestroy(): void {
this._destroy$.next();
this._destroy$.complete();
}
public handleError(error: Error | HttpErrorResponse): void {
console.log('Did i get called?', error);
const failFast: number[] = [401, 403, 500];
if (error instanceof HttpErrorResponse) {
if (navigator.onLine) {
if (failFast.includes(error.status)) {
handleFailFastError();
}
if (error.status === 409) {
//handleConflictError();
}
if (error.status === 400) {
//handleBadRequestError();
}
//handleAnythingElse();
} else {
//Errors, when the user is offline
//handleOfflineError();
}
} else {
//Type errors
console.log('Type Error',error);
//handleTypeError();
}
}
//functions
public handleFailFastError(): void {
console.log('Handled 500');
}
}
到目前为止,我使用旁观者和笑话进行的测试:
import {ErrorHandlerInterceptor} from './error-handler.interceptor';
import {createServiceFactory} from '@ngneat/spectator';
import {createSpyObject, SpectatorService} from '@ngneat/spectator/jest';
import {HttpErrorResponse} from '@angular/common/http';
import {CoreModule} from '@app/core/core.module';
describe('ErrorHandlerInterceptor', () => {
const createErrorHandler = createServiceFactory({
service: ErrorHandlerInterceptor,
imports: [CoreModule],
mocks: []
});
let specErrorHandler: SpectatorService<ErrorHandlerInterceptor>;
const dummyError = createSpyObject(HttpErrorResponse);
const handleError = (error: HttpErrorResponse): void => {
specErrorHandler.service.handleError(dummyError);
};
beforeEach(() => specErrorHandler = createErrorHandler());
it('should create the error handler', () => {
const errorHandler = specErrorHandler.service;
expect(errorHandler).toBeTruthy();
});
it('at least console should be called 2 times', () => {
const spyConsole = spyOn(console, 'log');
[500].forEach(status => {
handleError(new HttpErrorResponse({status}));
expect(spyConsole).toHaveBeenCalledTimes(5);
});
});
it('should redirect, and delete sessionStorage', () => {
[500].forEach(status => {
handleError(new HttpErrorResponse({status}));
expect(specErrorHandler.service.handleFailFastError).toBeCalled();
});
});
});