Angular 模拟多个 HTTP 调用

Muh*_*eer 8 rxjs typescript karma-jasmine angular angular-httpclient

我有一项服务,它返回多个 http 调用的 forkjoin。我想测试这个场景。

    class CommentService{
     addComments(){

let ob1 = Observable.of({});
    let ob2 = Observable.of({});
if(any condition)
        ob1 = {this.http.post('/url/1')};
if(any condition)
            ob2 = {this.http.post('/url/2'};
        return Observable.forkJoin(ob1,ob2)
           }
     }
Run Code Online (Sandbox Code Playgroud)

以上是我的服务类。我如何模拟 http 调用。

describe("CommentService", () => {
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule, HttpClientTestingModule],
      providers: [CommentService]
    });

    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);
  });

  it('addComments() call with normal and gate', inject([CommentService], (service: CommentService) => {


    let cmts = service.addComments();

    const reqGateComment = httpTestingController.expectOne('/url/1');
    expect(reqGateComment.request.method).toEqual('POST');

    const reqFactComment = httpTestingController.expectOne('/url/2');
    expect(reqFactComment.request.method).toEqual('POST');

    reqGateComment.flush({});
    reqFactComment.flush({});


    httpTestingController.verify();

    cmts.subscribe(results=>{
       expect(results.length).toEqual(2);
    });

  }));


});
Run Code Online (Sandbox Code Playgroud)

我得到以下测试失败。CommentService addFactsAndComments() 调用普通和门

错误:应为条件“匹配 URL:”的一个匹配请求:

 '/url/1", found none.
Run Code Online (Sandbox Code Playgroud)

Jot*_*edo 0

HttpClient那是因为您正在使用该方法将由 所创建的可观察量包装在新的可观察量中of

通过做

joined$ = forkJoin(obs$(post1$),obs$(post2$))
Run Code Online (Sandbox Code Playgroud)

注:$代表可观察的

您创建一个新的可观察量:

  • 订阅外部obs$
  • 等待他们完成,
  • 收集它们最后发出的值(在本例中为 post1$ 和 post2$)
  • 按照源流的顺序将收集到的值作为数组返回

因为我们只订阅了外部obs$,所以您的测试失败了

'/url/1",没有找到。

因为我们从未订阅过内部 post$,这意味着请求未发送。

将您的服务方式更改为:

addComments(){    
    const ob1 = this.http.post('/url/1');
    const ob2 = this.http.post('/url/2');

    return Observable.forkJoin(ob1,ob2);
 }
Run Code Online (Sandbox Code Playgroud)