RxJS first() for Observable.of() - no elements in sequence

六眼飞鱼酱① 提交于 2019-12-05 10:07:23

问题


For my tests I am trying to mock an event stream with Observable.of() but when I try

const actions$ = Observable.of({});
...
// in the function that is tested
actions$
  .filter(action => action.type === 'LOAD_REQUEST') 
  .first()
  .subscribe(() => { ... do something });

I get the following error

EmptyError: no elements in sequence in xxx.js

This only occurs when I use .first().

How can I mock the event stream so the tests don't fail?


回答1:


.first() will emit exactly one item or throw an error (if no defaultValue parameter was provided), so calling it on an empty observable will cause an error. This is the expected behavior based on the documentation.

If you would like to get at most one item from the observable, use .take(1).




回答2:


The documentation for first() says:

Delivers an EmptyError to the Observer's error callback if the Observable completes before any next notification was sent.

So the error happens because your test data don't pass the filter() operator and emit complete immediately.



来源:https://stackoverflow.com/questions/40848709/rxjs-first-for-observable-of-no-elements-in-sequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!