【问题标题】:RxJs Marble Test Fails When Using Observable.fromPromise使用 Observable.fromPromise 时 RxJs Marble 测试失败
【发布时间】:2018-09-26 17:04:22
【问题描述】:

我一直在尝试为简单的 redux-observable 史诗编写 RxJS 大理石测试,但无法通过。当在 testScheduler 上调用 flush 时,似乎在被测可观察链中使用 fromPromise 不会按照预期的弹珠序列发出项目。

提供测试样本。如果我将 Observable.fromPromise 替换为 Observable.of 测试将通过。

感谢任何见解。 RxJS 5 / redux-observable 0.18

...
const MY_ACTION = 'MY_ACTION';

const myAction = () => ({
  type: MY_ACTION,
  payload: {test: 'testval'},
});

const epic = action$ =>
  action$.ofType(MY_ACTION).switchMap(() =>
    Observable.concat(
      Observable.of({type: 'test1'}),
      Observable.fromPromise(Promise.resolve({type: 'test2'})),
    )
  );

it('it should work', () => {
  const deepEquals = (actual, expected) => {
    expect(actual).to.deep.equal(expected);
  };

  const createTestScheduler = () =>
    new TestScheduler(deepEquals);

  const marbles1 = '-a-';
  const marbles2 = '-(bc)-';
  const values = {
    a: myAction(),
    b: {type: 'test1'},
    c: {type: 'test2'},
  };

  const ts = createTestScheduler();
  const source = ActionsObservable.from(
    ts.createColdObservable(marbles1, values)
  );
  const actual = epic(source);


  ts.expectObservable(actual);

  ts.expectObservable(actual).toBe(marbles2, values);
  ts.flush();
});
...

【问题讨论】:

  • 问题是Promise.resolve是异步的,但是flush要求组合的observables是同步的或者使用测试调度器的虚拟时间概念。
  • 感谢您的回复,我可以查看 RxJS 文档中的任何地方以了解此约束吗?
  • 回答了我自己的问题 - 请参阅 github.com/ReactiveX/rxjs/pull/745github.com/ReactiveX/rxjs/issues/701 - 似乎不可能。

标签: unit-testing rxjs5 redux-observable


【解决方案1】:

查看“已知问题”部分下的文档:https://rxjs-dev.firebaseapp.com/guide/testing/marble-testing

您可以使用from 运算符来包装一个承诺,如下所示:

const myAsyncCode = () => from(Promise.resolve('something'));

it('has async code', (done) => {
  myAsyncCode().subscribe((d) => {
    assertEqual(d, 'something');
    done();
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-19
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    相关资源
    最近更新 更多