【问题标题】:async function test with Observable.delay in Angular Unit test not workingAngular 单元测试中使用 Observable.delay 的异步函数测试不起作用
【发布时间】:2018-04-03 12:42:44
【问题描述】:

这是我的模拟服务,延迟 10 毫秒:

class MockHttp {   
  post(url, body, option): Observable<Response> {
    let resOpt = new ResponseOptions({
      body: JSON.stringify({success: true})
    });
    let res: Response = new Response(resOpt);
    return Observable.of(res).delay(10);
  }
}

这是我的测试用例。

it('http post should get valid response without any param', fakeAsync(() => {
    let retVal = null;
    // note this is just blackbox testing. httpHelperSerivce.post() function is wrapper of http.post(p1, p2, p3), 
    httpHelperService.post('url', {a: 'a'}).subscribe(res => {
      console.log(res);
      retVal = res;
    });
    tick();
    expect(retVal).toEqual({success: true});
    discardPeriodicTasks();
  }));

测试不等待延迟。事不宜迟。

我的代码有什么问题吗? MockHttp 的延迟超出当前区域?

【问题讨论】:

  • 请注意,RxJS 使用setInterval 而不是setTimeout,所以如果没有模拟前者可能会解释问题。

标签: angular unit-testing jasmine rxjs observable


【解决方案1】:

我看不出你的测试有什么问题。

试试 Observable.timer(10).map(() => res).take(1) 而不是 Observable.of(res).delay(10)。

过去我也遇到过 rx 的 .delay() 和 jasmine.clock().tick() 的一些问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 2023-03-29
    • 1970-01-01
    • 2013-03-14
    相关资源
    最近更新 更多