【问题标题】:How to test angular http interceptors with injected objects如何使用注入的对象测试角度 http 拦截器
【发布时间】: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


    【解决方案1】:

    我认为您需要在您的提供商中提供您的Store&lt;AppState&gt;dependency。不像 HTTP_INTERCEPTORS 这样的 JSON,而是作为 providers 数组中的一个普通条目。当然也删除顶部的声明。您可以将TestBed 视为您的 NgModule 进行测试。因此,为了找到要注入的依赖项,Angular 会扫描它以查找您需要的令牌。不幸的是,如果你不这样做,你通常不会得到有用的错误。

    【讨论】:

      猜你喜欢
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      • 2014-02-09
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多