【问题标题】:Unit test async method with multiple awaits具有多个等待的单元测试异步方法
【发布时间】:2021-10-14 18:39:46
【问题描述】:

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

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

【问题讨论】:

    标签: javascript angular jasmine karma-jasmine angular-unit-test


    【解决方案1】:

    为了在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();
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      相关资源
      最近更新 更多