在单元测试期间,Observable.fromPromise为空 [英] Observable.fromPromise empty during unit testing
问题描述
loadAdList $
是一个Observable,它接入 actions $
stream:
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
方法返回一个promise。这是基于以下测试的结果:
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的上下文中同步解析。由于这些原因,如果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屋!