NGXS:测试调度的动作不适用于ofActionDispatched

时间:2018-11-27 15:31:30

标签: angular unit-testing jasmine store ngxs

我正在尝试测试动作分配,但是在我的测试中它不起作用... 组件运行良好,已分派了动作,但actions $ .pipe无法捕获该动作,因此无法在测试中进行检查。

代码:

describe('ResponsiveService', () => {
  let store, actions$;
  const observableMediaMock = {
    subscribe : (callback: (change: MediaChange) => void) => { 
      this.callback = callback 
    },
    triggerMediaChange: (change: MediaChange) => this.callback(change)
  };
  beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [
            FlexLayoutModule,
            NgxsModule.forRoot([MediaState])
        ],
        providers: [ResponsiveService, { provide: ObservableMedia, useValue: observableMediaMock }]
    });
    store = TestBed.get(Store);
    actions$ = TestBed.get(Actions);
  });

  it('should be created', inject([ResponsiveService], (service: ResponsiveService) => {
    expect(service).toBeTruthy();
  }));

  it("should send get request", function(done) {
    inject([ResponsiveService], (service: ResponsiveService) => {
      const mediaQueryValue = 'mediaQuery',
            mqAliasValue = 'mqAlias',
            suffixValue = 'suffix';

      actions$.pipe(ofActionDispatched([MediaChanged]))
      .subscribe(({payload}) => {
        expect(payload).toBeTruthy();
        expect(payload.mediaQuery).toEqual(mediaQueryValue);
        done();
      });
      service.init();

      observableMediaMock.triggerMediaChange(new MediaChange(null, mediaQueryValue, mqAliasValue, suffixValue));
    })(); // function returned by 'inject' has to be invoked
  });
});

谢谢!

1 个答案:

答案 0 :(得分:0)

将您的测试更新为以下内容:

it("should send get request", async( () => {
  inject([ResponsiveService], (service: ResponsiveService) => {
  const mediaQueryValue = 'mediaQuery',
        mqAliasValue = 'mqAlias',
        suffixValue = 'suffix';

  actions$.pipe(ofActionDispatched(MediaChanged))
  .subscribe(({payload}) => {
    expect(payload).toBeTruthy();
    expect(payload.mediaQuery).toEqual(mediaQueryValue);
  });
  service.init();

  observableMediaMock.triggerMediaChange(new MediaChange(null, mediaQueryValue, mqAliasValue, suffixValue));
  })(); // function returned by 'inject' has to be invoked
}));

ofActionDispatched不会将列表作为输入,但是评估者会使用项目列表,例如:ofActionDispatched(MediaChanged, SomeOtherAction)

您还应该能够删除done函数,而只需将测试包装在常规async块中。希望这会有所帮助,不确定我是否正确打开和关闭了所有括号。