【发布时间】:2018-07-16 05:12:23
【问题描述】:
如果后端以 419 状态码响应(我们用它来表示用户会话已过期),我正在尝试测试我的拦截器是否将正确的操作分派到 ngrx 存储。
如果我手动尝试它就可以工作 - 但我无法获得单元测试来验证这一点。打电话给我的商店从来没有发生过。我假设我监视的商店不是注入拦截器的商店,或者我希望以某种方式提前调用?
这是我目前的代码:
fdescribe('Http Session Timeout Interceptor', () => {
let store: Store<AppState>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, StoreModule.forRoot(appReducers)],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: HttpSessionTimeoutInterceptor,
multi: true
}]
});
store = TestBed.get(Store);
spyOn(store, 'dispatch');
});
it('interceptor is called',
inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) => {
http.get('/api').subscribe(response => {
const cast = response as HttpResponse<String>;
expect(cast.status).toBe(419);
});
const req = httpMock.expectOne('/api');
req.flush(<HttpResponse<String>>{status: 419});
httpMock.verify();
expect(store.dispatch).toHaveBeenCalledWith(new SessionTimeOutAction());
}));
});
这是拦截器,只是检查响应状态并调度动作:
@Injectable()
export class HttpSessionTimeoutInterceptor implements HttpInterceptor {
constructor(private store: Store<AppState>) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
.catch(response => {
if (response.status === 419) {
this.store.dispatch(new SessionTimeOutAction());
}
return Observable.throw(response);
}) as any;
}
}
【问题讨论】:
标签: angular typescript jasmine