import { TestBed } from '@angular/core/testing'; import { ErrorInterceptor } from './error.interceptor'; import { HttpClientTestingModule } from '@angular/common/http/testing';
describe('ErrorInterceptor', () => { let errorInterceptor: ErrorInterceptor;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [ErrorInterceptor]
});
errorInterceptor = TestBed.inject(ErrorInterceptor);
});
});
const mockErrorResponse = { status: 404, statusText: 'Not Found' }; const mockError = new Error('Not Found');
it('should intercept errors', () => { const httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']); httpClientSpy.get.and.returnValue(asyncError(mockErrorResponse));
const next: HttpHandler = {
handle: req => {
throw mockError;
}
};
errorInterceptor.intercept(null, next).subscribe(
() => fail('expected an error, not a successful result'),
error => {
expect(error).toEqual(mockErrorResponse);
}
);
});
it('should intercept errors', (done: DoneFn) => { const httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']); httpClientSpy.get.and.returnValue(asyncError(mockErrorResponse));
const next: HttpHandler = {
handle: req => {
throw mockError;
}
};
errorInterceptor.intercept(null, next).subscribe(
() => fail('expected an error, not a successful result'),
error => {
expect(error).toEqual(mockErrorResponse);
done();
}
);
});
使用这些步骤能够测试ErrorInterceptor拦截器。