NGXS。分派操作后如何测试服务方法(toHaveBeenCalled)

时间:2020-08-14 17:03:14

标签: angular karma-jasmine ngxs

我尝试运行测试,但是每次测试都会失败。我做错了

1。我的商店操作

@Action(GetDataAction)
  getDataList(ctx: StateContext<any>) {
    const state = ctx.getState();
    return this.service.getData()...

2。添加初始化变量。 在这里,我正在测试用例中创建一个服务变量。据我了解,我的服务将成为所有人的服务。


    describe('Store', () => {
      let actions$: Observable<any>;
      let store: Store;
      let service: SomeService;
    
      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [HttpClientModule, NgxsModule.forRoot([AppStore])],
        });
        store = TestBed.inject(Store);
        actions$ = TestBed.inject(Actions);
        service = new SomeService(null);
      });

3。添加测试

  it(should be run service.getData() after action new GetDataAction()', (done) => {

    const spy = spyOn(service, 'getData').and.callFake(() => {
      return EMPTY;
    });

    store.dispatch(new GetDataAction()).subscribe(() => {
      expect(spy).toHaveBeenCalled();
      done();
    });
  });

Error text: Store > should be run service.getData() after action new GetDataAction() Expected spy getData to have been called. Error: Expected spy getData to have been called. at <Jasmine> at SafeSubscriber._next (http://localhost:9876/_karma_webpack_/src/app/store/store.spec.ts:41:19) at SafeSubscriber.__tryOrUnsub (http://localhost:9876/_karma_webpack_/node_modules/rxjs/_esm2015/internal/Subscriber.js:183:1) at SafeSubscriber.next (http://localhost:9876/_karma_webpack_/node_modules/rxjs/_esm2015/internal/Subscriber.js:122:1)

0 个答案:

没有答案