我想测试一下,如果一个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));
}
通过这个Jasmine测试
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 }) }) ].
答案 0 :(得分:2)
当你catch
observable的错误时,它会从catch的结果选择器发出返回值,并且正常完成 observable,因为它不会发出error
。因此,期望的大理石输出为-(c|)
,其中值被发出并且可观察到的立即完成。