【发布时间】:2019-01-26 05:34:32
【问题描述】:
我想从消费者的角度测试 observable 的行为方式。
我不知道当我订阅(冷)或不订阅(热)时是否会有副作用。
有没有办法在单元测试中验证这种行为?
我已经连接了来自 rxjs/testing 的 TestScheduler,但我没有看到一个很好的方法来验证 observable 的创建次数。
// ...the create method has been mocked to emit after 3 frames
const create$ = api.create(potato).pipe(
tap(console.log.bind(null, 'object created'))
);
create$.subscribe();
create$.subscribe();
create$.subscribe();
// Test how many times create$ has gotten a subscription, generated a cold observable, and completed.
const timing = '---(a|)'; // wait 3 frames, emit value of `a`, complete
const values = { a: potato };
expectObservable(create$).toBe(timing, values);
此测试通过,但“对象已创建”消息触发了四次(3 次用于我的订阅,1 次来自中间件)。
我想在更改 observable 的行为以匹配我想要的 api.create 之前编写一个失败的测试(真否定)。
如何验证创建行为只执行一次?
我试过了:
-
spyOn,但实际的create方法只调用一次。 -
Array.isArray(create$.observers)-- 太间接了,只检查它是否热,而不是它的行为是否符合预期。 -
tap(() => runCount++)\expect(runCount).toBe(1)-- 如果我刷新调度程序,则有效,但似乎超出了 rxjs 测试的规范。 - 使用带有工厂功能的
Observable.create手动跟踪运行计数。也有效,有点冗长。
【问题讨论】:
标签: unit-testing rxjs