开玩笑 - 在 jest.setTimeout.Error 指定的 5000 毫秒超时内未调用异步回调

Jest - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error

我可以看到 SO 上有很多关于此的问题,但其中 none 回答了我的问题。

我有以下测试

 it('will poll until there are no subscribers', () => {
    const polls: string[] = [];
    const complete = new Subject<void>();
    const observableSub = service
      .getPollData()
      .pipe(takeUntil(complete))
      .subscribe((value) => {
        polls.push(value);
        if (polls.length === 3) {
          console.log('here ' + JSON.stringify(polls));
          observableSub.unsubscribe();
          complete.next();
          complete.complete();
        }
      });

    return complete.toPromise().then(() => {
      console.log(service.isPolling);
      expect(service.isPolling).toEqual(false);
    });
  });

当测试运行时,我的两个控制台日志都存在并且具有正确的预期值。这一切都在 20 毫秒内发生,我的测试频率设置为 5 毫秒。

我查看了我能找到的每个 SO post,我尝试使用 asyncasync(done) => done()fakeAsync,但似乎没有任何效果。我总是收到以下错误:

Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.

注意:我正在为响应注入一个 MockInterceptor 并且该服务正在使用 RxJs timer() observable 进行轮询,我可以确认这在测试结束时已关闭并取消订阅,这由 expect(service.isPolling) 行代码确认。我曾尝试使用 jest.userRealTimersjest.useFakeTimers 以防这是问题的一部分,但我的控制台日志显示预期值这一事实让我认为这不是问题所在。

如有任何帮助,我们将不胜感激。

*按照@Estus Flask 的建议进行更新我现在已经将代码更新为:

it('will poll until there are no subscribers', async () => {
      const polls: any[] = [];
      const observableSub = service.getPollData().pipe(
      take(3),
      tap((value) => {
        polls.push(value);
      })
    );
      await observableSub.toPromise().then(() => {
      console.log(JSON.stringify(polls));
      console.log(service.isPolling);
      expect(service.isPolling).toEqual(false);
    });
 });

但是还是报同样的错误,感觉自己doing/missing简单又愚蠢?!?!?注意:控制台输出仍然全部正确。

如果其他人遇到此问题,则值得查看测试集中的其他测试。

事实证明,对我来说,上述测试通过得很好,但是使用 setTimeout 进行的后续测试失败了。这让 Jest 感到困惑,然后将通过的测试标记为失败!

我在这上面浪费了很多时间,所以希望这对以后的人有所帮助。

您尝试过使用 done 吗?

it('will poll until there are no subscribers', async (done) => {
      const polls: any[] = [];
      const observableSub = service.getPollData().pipe(
      take(3),
      tap((value) => {
        polls.push(value);
      })
    );
      await observableSub.toPromise().then(() => {
      console.log(JSON.stringify(polls));
      console.log(service.isPolling);
      expect(service.isPolling).toEqual(false);
      done()
    });
 });