单元测试重试 websocket



我想对下面的函数进行单元测试,看看是否有 n 次 websocket 连接的重试

ws = webSocket(url)
notification(action: string) {
return this.ws.asObservable().pipe(
retryWhen(errors =>
errors.pipe(concatMap((_, iteration) =>
timer(Math.pow(2, iteration) * 1000)),
tap(e => console.log('test', e)),
take(10))
),
tap(e => console.log('st', e)),
filter((e: any) => e.action === action));
}

我有点纠结于如何模拟网络套路

it('should make call 10 times', fakeAsync(() => {
const service = TestBed.get(NotificationService);
let wsSpy = new Subject()
service.ws = wsSpy;
service.filterNotification('test').subscribe(data => {
expect(data).toBe('data')
})
wsSpy.error({ action: 'test' })
tick(time)
wsSpy.error({ action: 'test' })
// sending error the first time cancels the subscription
// Is there any other way to send the error many times
wsSpy.next({ action: 'test' })
}));

为了模拟失败的 websocket,我创建了以下函数,该函数关闭重试次数

function mockWs() {
let i = 0;
return function () {
return Observable.create((obs: Observer<any>) => {
i++;
if (i < 10) {
obs.error(new Error('attempt' + i));
} else {
obs.next(mockData);
obs.complete();
}
})
}
}
const wsMockSpy = mockWs();

然后,我不得不监视主题的可观察属性以提供模拟

spyOn(service.ws, 'asObservable').and.callFake(wsMockSpy);

整个单元测试如下所示

it('should try multiple times', fakeAsync(() => {
service = TestBed.get(NotificationService);
const mockData = { action: 'testMultiple' };
function mockWs() {
let i = 0;
return function () {
return Observable.create((obs: Observer<any>) => {
i++
console.log('i', i)
if (i < 10) {
obs.error(new Error('val' + i));
} else {
obs.next(mockData);
obs.complete();
}
})
}
}
const wsMockSpy = mockWs();
spyOn(service.ws, 'asObservable').and.callFake(wsMockSpy);
service.notification('testMultiple').subscribe(data => {
expect(data).toEqual(mockData)
})
tick(1230000)
}) )

最新更新