mercredi 24 juin 2020

How to test multiple requests in pipeline in Angular?

I want to test 3 requests done inside a pipeline. Simplified example:

    httpClient.get<Data[]>(testUrl)
      .pipe(
        mergeMap(() => range(0, 2)),
        mergeMap(() => httpClient.get<Data[]>(testUrl)),
      )

I'm using the official recommendation: HttpTestingController. It works fine if I have the requests one after another with httpTestingController.match. However, that's not how my real app is written. It's using pipes.

    let testData: Data[] = [
      { name: 'bob' }, { name: 'carol' },
      { name: 'ted' }, { name: 'alice' }
    ];

    // Make three requests in a row
    httpClient.get<Data[]>(testUrl)
      .subscribe(d => expect(d.length).toEqual(0, 'should have no data'));

    httpClient.get<Data[]>(testUrl)
      .subscribe(d => expect(d).toEqual([testData[0]], 'should be one element array'));

    httpClient.get<Data[]>(testUrl)
      .subscribe(d => expect(d).toEqual(testData, 'should be expected data'));

    // get all pending requests that match the given URL
    const requests = httpTestingController.match(testUrl);
    expect(requests.length).toEqual(3);

    // Respond to each request with different results
    requests[0].flush([]);
    requests[1].flush([testData[0]]);
    requests[2].flush(testData);

How to make httpTestingController.match work with multiple HTTP requests inside a pipe?

This is what I have tried so far and here is the reproducible example:

    httpClient.get<Data[]>(testUrl)
      .pipe(
        mergeMap(() => range(0, 2)),
        tap(console.log),
        mergeMap(() => httpClient.get<Data[]>(testUrl)),
        tap(console.log),
      )
      .subscribe(d => expect(d.length).toEqual(0, 'should have no data')); 

    const requests = httpTestingController.match(testUrl);
    console.log({requests}); // <--- why only one??

    requests[0].flush([]);

    // Error: Expected no open requests, found 2: GET /data, GET /data

https://stackblitz.com/edit/angular-http-testing2?file=src%2Ftesting%2Fhttp-client.spec.ts

Aucun commentaire:

Enregistrer un commentaire