Observable.fromPromise 在单元测试期间为空 [英] Observable.fromPromise empty during unit testing

查看:18
本文介绍了Observable.fromPromise 在单元测试期间为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

loadAdList$ 是一个利用 actions$ 流的 Observable:

loadAdList$ is an Observable that taps into the actions$ stream:

loadAdList$: Observable<Action> = this.actions$
    .ofType<adActions.Load>(adActions.LOAD)
    .switchMap((action) => {
      return Observable.fromPromise(store.findAll('ad', action.payload)
        .then((ads) => {
          return new adActions.LoadSuccess(ads);
        })
        .catch((err) => {
          return new adActions.LoadFail(err);
        }));
    });

它在浏览器中工作,没有问题.但是,我也想对其进行单元测试:

It works in the browser, there is no problem with it. However, I want to unit test it as well:

actions$ = hot('-a', { a: loadAction });
const storeResponse = Promise.resolve(mockAds);
const expected$ = cold('-c', { c: loadSuccessAction });

spyOn(store, 'findAll').and.returnValue(storeResponse);

expect(effects.loadAdList$).toBeObservable(expected$);

测试失败并显示以下内容:

The test fails with the following:

Expected 

to deep equal 
    {"frame":10,"notification":{"kind":"N","value":{"payload":"[
    ...

我认为该问题与返回承诺的 store.findAll 方法有关.这是基于以下测试的结果:

I believe the issue has something to do with the store.findAll method returning a promise. This is based on the results of the following test:

.switchMap((action) => {
  // This test will pass
  return Observable.from([new adActions.LoadSuccess(mockAds)]);

  // This test will fail
  return Observable.fromPromise(Promise.resolve(new adActions.LoadSuccess(mockAds)));

});

推荐答案

有点遗憾,但是在 Rx v5 中的 TestScheduler 的上下文下,没有很好的方法来使 promise 同步解析.出于这些原因,如果 Observable 源从 promise 开始,它将不适用于大理石测试,并且您必须通过订阅来创建不同的断言.

It is bit unfortunate but there wasn't great way to make promise resolves synchronously under context of TestScheduler in Rx v5. For those reason, if Observable source started off from promise it won't work with marble testings and you have to create assertion differently by subscribing.

检查 https://github.com/ReactiveX/rxjs/issues/701/https://github.com/ReactiveX/rxjs/pull/745 如果你'想详细说明为什么没有成功.

Check https://github.com/ReactiveX/rxjs/issues/701 / https://github.com/ReactiveX/rxjs/pull/745 if you'd like to have detail why it wasn't successful.

这篇关于Observable.fromPromise 在单元测试期间为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆