使用ng2-redux进行Angular 4.4测试服务(angular-redux)

时间:2017-12-02 00:28:16

标签: angular testing

我无法在我的服务中捕获调度方法。据我所知,存在问题,因为我需要的调度是Observable.subscribe()。

这是服务:

@Injectable()
export class AuthUserBackendService extends BaseBackendDataService{

constructor(
 private http: Http,
 private tokenLoader: TokenLoaderBackendService,
 private ngRedux: NgRedux<IAppState>,
 private logger: LoggerService,
 private errorService: BackendDataErrorsService
) {
  super(http, tokenLoader, ngRedux, logger, errorService);
} 
........
testMethod() {

// this dispatch ok
// this.ngRedux.dispatch({type: 
ActiontionsBackendData.authUserBackendActions.startHttpRequestAuthUser});

Observable.of({Id: 'testId', Name: 'TestName'}).delay(100).subscribe(
  (result) => {

    const payload = {authUser: result};

    // this dispatch I can't catch in test
    this.ngRedux.dispatch({type: ActionsBackendData. authUserBackendActions. 
    receivedAuthUserHttpResponseSuccess, payload: payload});
   });
 }
}

这是我的.spec.ts

let testService: AuthUserBackendService;
let mockState: any = {
authUserState: {
  authUser: null
 }
};
let mockRedux: NgRedux<IAppState> = new MockRedux(mockState);


describe('AuthUserBackendService', () => {

beforeEach(() => {
TestBed.configureTestingModule({
  imports: [
    ToastyModule,
    TranslateModule.forRoot(),
    NgReduxModule,
    LoggerModule,
    MockBackendModule,
    RouterTestingModule.withRoutes([]),
    BackendDataModule,
    CoreModule
  ],
  providers: [
    {provide: Router, useClass: RouterTestingModule},
    {provide: NgRedux, useValue: mockRedux},

  ]
});



  testService = TestBed.get(AuthUserBackendService);

 });

  it('should be created', () => {
    expect(testService).toBeTruthy();
  });

 describe('testMethod()', ()=>{

it('catch dispatch calls count', ()=> {

  const spy = spyOn(mockRedux, 'dispatch');

  testService.testMethod();

  expect(spy.calls.count()).toEqual(1);

  });

 });

});

因此,对于'catch dispatch calls count',我得到预期的0等于1.如果我取消注释第一次调度,测试将是正常的,但这意味着,我无法在订阅区域中捕获调度。怎么了?非常感谢你的建议。

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。这是规范的正确代码。也许有另一种方式,但我找到了它

....

describe('testMethod()', ()=>{

  it('catch dispatch calls number', fakeAsync(()=> {

    const spy = spyOn(mockRedux, 'dispatch');

    testService.testMethod();

    tick(120); // in general it must be more then delay

    expect(spy.calls.count()).toEqual(1);

  }));


});