Unittest Angular4效果和HttpClient

时间:2017-11-08 20:58:52

标签: angular unit-testing ngrx ngrx-effects

我有一个正在运行的Angular 4.4.6应用程序(NgRx 2.x),我正在迁移到新的HttpClient。迁移后一切正常,除了单位测试。

我有1个@Effect执行HttpClient.get并返回一个简单的JSON响应。 在单元测试中,我在效果中获得了一个'无法读取属性'数据'未定义',在运行应用程序时工作正常。

任何指示我做错了什么? 我没想到的是@Effect catch中的console.log行(获取'未读'属性'未定义'TypeError的数据'。

效果

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';
import { Observable } from 'rxjs/Observable';
import { LOAD_SESSION_DATA, LoadSessionDataFailedAction, LoadSessionDataSuccessAction } from './session-data.actions';
import { SessionData } from './session-data.model';

@Injectable()
export class SessionDataEffects {

  @Effect() loadSessionData$ = this.actions$
    .ofType(LOAD_SESSION_DATA)
    .switchMap(() => this.httpClient.get('/session-data')
      .map((data: SessionData) => new LoadSessionDataSuccessAction({data}))
      .catch((err) => {
        console.log(err.message);
        return Observable.of(new LoadSessionDataFailedAction());
      }));

  constructor(private actions$: Actions,
              private httpClient: HttpClient) {
  }
}

单元测试

import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { EffectsRunner, EffectsTestingModule } from '@ngrx/effects/testing';
import { StoreModule } from '@ngrx/store';
import { AppModule } from '../../app.module';
import { LoadSessionDataAction, LoadSessionDataSuccessAction } from './session-data.actions';
import { SessionDataEffects } from './session-data.effects';
import { SessionData } from './session-data.model';
import { sessionDataReducer } from './session-data.reducer';

describe('SessionData effects', () => {
  let runner: EffectsRunner;
  let effects: SessionDataEffects;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        AppModule,
        EffectsTestingModule,
        StoreModule.provideStore(sessionDataReducer)
      ]
    });

    runner = TestBed.get(EffectsRunner);
    effects = TestBed.get(SessionDataEffects);
    httpMock = TestBed.get(HttpTestingController);
  });

  it('should return a LoadSessionDataSuccessAction', () => {
    const stubResponseBody: SessionData = {datasource: 'test-datasource'};
    runner.queue(new LoadSessionDataAction());

    effects.loadSessionData$.subscribe(result => {
        expect(result).toEqual(new LoadSessionDataSuccessAction({data: stubResponseBody}));
      });

    const req = httpMock.expectOne('/session-data');
    req.flush(stubResponseBody);
  });
});

0 个答案:

没有答案