我正在尝试为以下使用运算符的函数编写测试retryWhen
:
// some API I'm using and mocking out in test
import { geoApi } from "api/observable";
export default function retryEpic(actions$) {
return actions$.pipe(
filter(action => action === 'A'),
switchMap(action => {
return of(action).pipe(
mergeMap(() => geoApi.ipLocation$()),
map(data => ({ data })),
retryWhen(errors => {
return errors.pipe(take(2));
}),
);
}),
);
}
该代码应该执行对某个远程 API 的请求geoApi.ipLocation$()
。如果出现错误,它会在放弃之前重试 2 次。
我编写了以下使用 Jest 和 RxJS TestScheduler 的测试代码:
function basicTestScheduler() {
return new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
}
const mockApi = jest.fn();
jest.mock('api/observable', () => {
return {
geoApi: {
ipLocation$: (...args) => mockApi(...args),
},
};
});
describe('retryEpic()', () => {
it('retries fetching 2 times before succeeding', () => {
basicTestScheduler().run(({ hot, cold, expectObservable, expectSubscriptions }) => {
const actions$ = hot('-A');
// The first two requests fail, third one succeeds
const stream1 = cold('-#', {}, new Error('Network fail'));
const stream2 = cold('-#', {}, new Error('Network fail'));
const stream3 = cold('-r', { r: 123 });
mockApi.mockImplementationOnce(() => stream1);
mockApi.mockImplementationOnce(() => stream2);
mockApi.mockImplementationOnce(() => stream3);
expectObservable(retryEpic(actions$)).toBe('----S', {
S: { data: 123 },
});
expectSubscriptions(stream1.subscriptions).toBe('-^!');
expectSubscriptions(stream2.subscriptions).toBe('--^!');
expectSubscriptions(stream3.subscriptions).toBe('---^');
});
});
});
此测试失败。
但是,当我用retryWhen(...)
simple替换时retry(2)
,测试成功。
看起来我不太明白如何retry
用retryWhen
. 我怀疑这take(2)
正在关闭流并阻止一切继续进行。但我不太明白。
我实际上想在里面写一些额外的逻辑retryWhen()
,但首先我需要了解如何正确实现retry()
with retryWhen()
。或者这实际上是不可能的?
其他资源
我的retryWhen
+实现take
基于这个 SO 答案:
官方文档: