【问题标题】:Unit testing retries websocket单元测试重试 websocket
【发布时间】:2019-11-28 11:42:43
【问题描述】:

我想对下面的函数进行单元测试,看看是否有 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));
  }

我对如何模拟 websocket 有点困惑

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' })
  }));

【问题讨论】:

    标签: angular unit-testing jasmine


    【解决方案1】:

    为了模拟失败的 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();
    

    然后,我不得不监视对象的属性 asObservable 以提供模拟

    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)
      }) )
    

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 2022-07-25
      • 2014-05-24
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多