3

I trying to test an interceptor that adds a finalize operator to the pipeline and i'm unable to keep the test running long enough for the returned observable to, y'know, finalize.

Here's the observable returned from the intercept function:

return next.handle(request).pipe(
    finalize(() => {
      console.log('int finalize');
      this.activeRequests--;
      if (this.activeRequests === 0 ) {
        this.loader.endLoading();
      }
    }));

I'm trying to test that the return object calls endLoading

beforeEach(() => spyOn(svc, 'endLoading').and.callThrough());

fit('calls endLoading', async(() => {
  const expected = [];
  client.get('/someUrl')
    .pipe(
      finalize(() => {
        console.log('spec finalize');
        expect(svc.endLoading).toHaveBeenCalledTimes(1);
      })
    ).subscribe(response => expect(response).toEqual(expected));

  http.expectOne('/someUrl').flush(expected);
  expect(svc.endLoading).toHaveBeenCalledTimes(1);
}));

When the test executes, the console outputs spec finalize before int finalize regardless of whether i use async, fakeAsync or done. I suspect loading the whole setup into a component stub and chaining whenStable calls would work, but it seems like there should be a better way. Any suggestions?

The Head Rush
  • 3,157
  • 2
  • 25
  • 45
  • You should use `fakeAsync()` instead of `async()`. You can then flush the microtasks waiting using `flush()` or `tick(10000)`. – Reactgular Jul 23 '19 at 19:07
  • You should also use the mocking module for HttpClient. https://medium.com/netscape/testing-with-the-angular-httpclient-api-648203820712 – Reactgular Jul 23 '19 at 19:08
  • Could you show your solution using `done` etc.? Its possible you put it in the wrong place. – James Jul 23 '19 at 19:13

0 Answers0