【问题标题】:Issue when testing ngrx effects with jest and jasmine-marbles使用 jest 和 jasmine-marbles 测试 ngrx 效果时的问题
【发布时间】:2019-02-06 10:18:37
【问题描述】:

我正在使用jestjasmine-marbles 来测试我的ngrx-effects。到目前为止一切顺利,但我有一个特殊情况,我需要使用withLatestFrom 来访问Store,这样的效果如下:

@Effect()
createDataSourceSuccess$ = this.actions$
  .ofType<sourceActions.CreateDataSourceSuccess>(
    sourceActions.DataSourceActionTypes.CreateDataSourceSuccess
  )
  .pipe(
    map(action => action.dataSource),
    withLatestFrom(this.store.select(getSourceUploadProgress)),
    switchMap(([source, progress]: [DataSource, UploadProgress]) =>
     of(
        new sourceActions.StartSourceUploadProgress({
          id: source.fileId,
          uploadProgress: progress,
        })
      )
    )
  );

我也确实像这样设置了我的测试:

it('should return StartSourceUploadProgress for CreateDataSourceSuccess', () => {
  const dataSource = dataSources[0];
  const action = new dataSourceActions.CreateDataSourceSuccess(dataSource);
  const outcome = new dataSourceActions.StartSourceUploadProgress({
    id: dataSource.fileId,
    uploadProgress: null,
  });

  store.select = jest.fn(_selector => of(null));

  actions.stream = hot('-a-', { a: action });
  const expected = cold('--b', { b: outcome });

  expect(effects.createDataSourceSuccess$).toBeObservable(expected);
});

我还注意到我成功地为StoreActions 设置了模拟,因为所有其他测试都可以正常工作。这个和其他的唯一区别是StorewithLatestFrom在这些效果中不存在。

最后这是我得到的错误输出:

 DataSourceEffects › should return StartSourceUploadProgress for CreateDataSourceSuccess

    TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

有什么想法吗?

【问题讨论】:

    标签: angular ngrx ngrx-effects jasmine-marbles


    【解决方案1】:

    这个解决方案对我有用

    it('should return StartSourceUploadProgress for CreateDataSourceSuccess', () => {
      const dataSource = dataSources[0];
      const action = new dataSourceActions.CreateDataSourceSuccess(dataSource);
      const outcome = new dataSourceActions.StartSourceUploadProgress({
        id: dataSource.fileId,
        uploadProgress: null,
      });
    
      actions.stream = hot('-a-', { a: action });
      const expected = cold('--b', { b: outcome });
    
      store.select = jest.fn().mockImplementationOnce(() => of(new SourceUploadProgress()));
    
      expect(effects.createDataSourceSuccess$).toBeObservable(expected);
    });
    

    【讨论】:

    • 建议的解决方案到底是什么?我将jest.fn(_selector =&gt; of(null)) 更改为jest.fn().mockImplementationOnce(() =&gt; of(null)),但仍然出现同样的错误。
    • 尝试在 mockImpl 中使用coldjest.fn().mockImplementationOnce(() =&gt; cold('a', {a: null}))
    • 这对我不起作用。由于某些潜在错误,效果似乎无法获取操作流。
    猜你喜欢
    • 2018-01-04
    • 2019-10-24
    • 2018-05-15
    • 1970-01-01
    • 2023-03-13
    • 2019-01-14
    • 2021-04-07
    • 1970-01-01
    • 2019-10-13
    相关资源
    最近更新 更多