具有多个等待的单元测试异步方法

Unit test async method with multiple awaits

我试图在第一次等待后测试语句,但它不起作用。调试器没有命中下一个断点

service.ts

async deleteFaq(faq: FaqDetailsApi) {
  await this._http.delete(`${this.ADMIN_FAQ_URL}/${faq.id}`).toPromise();

  debugger // Debugger doesn't hit this, next lines are not executed

  await this._http.get(`${this.ADMIN_FAQ_URL}/${faq.order}/-1/${faq.id}`).toPromise();
  const faqPrev = this._faqs.getValue().find(f => f.id === faq.id);
}

service.spec.ts

it('should create a DELETE request 123', fakeAsync(() => {
  let faq = testFaqs[0];
  service.deleteFaq(faq);
  const req = httpMock.expectOne(`${service.ADMIN_FAQ_URL}/${faq.id}`);
  tick();
  expect(req.request.method).toBe('DELETE'); // pass
  const req2 = httpMock.expectOne(`${service.ADMIN_FAQ_URL}/${faq.order}/-1/${faq.id}`);
  tick();
  expect(req2.request.method).toBe('GET'); // fails
}));

为了在 await 之后继续执行,您需要满足两件事:

  • 通过模拟http请求解析并完成Observable
  • 模拟Promise的异步通道

您已经使用 tick() 解决了第二种情况,但如果不模拟 http 请求,它什么也不做。

为此使用 TestRequest#flush 方法:

const req = httpMock.expectOne(`${service.ADMIN_FAQ_URL}/${faq.id}`);
req.flush({}); // synchrounously simulates http request and complete observable
tick();
...