我的测试中有一个问题,即使必须将其淘汰,也总是可以的。 我创建了一个拦截器
@Injectable()
export class ErrorHttpInterceptor implements HttpInterceptor {
constructor(private store: Store<RoutingCustom>) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
tap(
() => {},
(err: object) => {
if (err instanceof HttpErrorResponse && err.status === 501) {
this.store.dispatch(
RoutingCustom.login()
);
}
}
)
);
}
}
我做了测试以验证我的拦截器
describe('ErrorHttpInterceptor', () => {
let httpMock: HttpTestingController;
let httpClient: HttpClient;
let store: MockStore<RoutingInterface.RouterState>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [],
imports: [HttpClientTestingModule],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: ErrorHttpInterceptor,
multi: true
},
provideMockStore()
]
});
store = TestBed.get(Store);
httpClient = TestBed.get(HttpClient);
httpMock = TestBed.get(HttpTestingController);
});
test('error 501', () => {
spyOn(store, 'dispatch').and.stub();
httpClient.get('/test').subscribe(
data => {},
error => {
expect(store.dispatch).toHaveBeenCalledTimes(4);
}
);
const req = httpMock.expectOne(`/test`);
req.flush('Error', { status: 501, statusText: 'Error' });
});
});
但是我可以将0或15放入toHaveBeenCalledTimes方法中,我仍然可以通过测试。 有人有测试拦截器的想法吗?
谢谢