好吧,jasmine-marbles 实际上提供了一个非常方便的匹配器来测试流的输出,因此您不必以某种方式手动触发调度器:.toBeObservable
. 您可以通过将另一个流传递给它来使用它,即预期的输出。
我将稍微更改您的示例以显示其用途。假设我们在真实模块中测试从一个流到另一个流的映射,它接受一个字符串并发出一个布尔值。
// real-module.ts
import { Observable, Subject } from 'rxjs';
import { map } from 'rxjs/operators';
export const input$: Subject<string> = new Subject ();
export const output$: Observable<boolean> = input$.pipe (map (value => ({
IWantTheTruth : true,
ICantHandleTheTruth : false
}[value])));
// real-module.spec.ts
import { cold } from 'jasmine-marbles';
import { input$, output$ } from './real-module';
const schedule$ = cold ('--x--y|', { x : 'IWantTheTruth', y : 'ICantHandleTheTruth' });
const expected$ = cold ('--x--y|', { x : true, y : false });
schedule$.subscribe (input$);
expect (output$).toBeObservable (expected$);
匹配器为您运行测试调度程序,并比较实际和预期流的结果,就好像它只是比较两个普通的可迭代对象一样。如果您故意使测试失败,您可以看到这一点:
expect (cold ('-x')).toBeObservable (cold ('x-'));
此失败测试的输出错误消息如下所示(为了清楚起见,我添加了换行符):
Expected [
Object({ frame: 10, notification: Notification({ kind: 'N', value: 'x', error: undefined, hasValue: true }) })
] to equal [
Object({ frame: 0, notification: Notification({ kind: 'N', value: 'x', error: undefined, hasValue: true }) })
].
您可以看到 的值frame
是不同的,因为弹珠中的时间不同。Notification 对象显示发出的内容的详细信息。kind
是'N'
for next、'E'
for error 或'C'
for complete 之一。