我想测试一下,如果一个 observable 从它的一个操作符内部捕获了一个抛出的错误,我会得到预期的结果 observable。
下面的服务根据其错误参数返回一个是否引发错误的可观察对象。
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/merge';
import 'rxjs/add/operator/do';
import 'rxjs/add/observable/of';
export function service(obs1: Observable<number>, obs2: Observable<number>, error: boolean = false) {
return obs1.merge(obs2)
.map((elt) => elt * 2)
.do(() => {
if (error) {
throw new Error();
}
})
.catch(() => Observable.of(0));
}
有了这个茉莉花测试
import { cold } from 'jasmine-marbles';
import { Observable } from 'rxjs/Observable';
import { service } from './catch';
describe('Test Marbles', () => {
it('should work', () => {
const e1 = cold('-a-|', {a: 1});
const e2 = cold('--b-|', {b: 2});
const expected = cold('-ab-|', {a: 2, b: 4});
const obs: Observable<number> = service(e1, e2);
expect(obs).toBeObservable(expected);
});
it('should handle error', () => {
const e1 = cold('-a-|', {a: 1});
const e2 = cold('--b-|', {b: 2});
const expected = cold('-c', {c: 0});
const obs: Observable<number> = service(e1, e2, true);
expect(obs).toBeObservable(expected);
});
});
对于第二次失败的测试,我得到了下面的输出。
Expected [ Object({ frame: 10, notification: Notification({ kind: 'N', value: 0, error: undefined, hasValue: true }) }), Object({ frame: 10, notification: Notification({ kind: 'C', value: undefined, error: undefined, hasValue: false }) }) ] to equal [ Object({ frame: 10, notification: Notification({ kind: 'N', value: 0, error: undefined, hasValue: true }) }) ].