Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test code executed in .finally()

Tags:

rxjs

The finally works as described here.

How do I test code that is run in finally?

// code
function doCall(body) {
  isWaitingForRequestToComplete();
  return this.apiService
    .someRequest(body)
    .map(response => transform(response))
    .catch(error => Observable.of('Request failed: ' + error.message))
    .finally(() => {
      requestHasCompleted()
      console.log("Finally");
    });
}

// unit test
it('test observable', () => {
  const testBody = {};
  doCall(testBody).subscribe(() => {
    expect(isWaitingForRequestToComplete).toHaveBeenCalled();
    expect(apiService.someRequest).toHaveBeenCalled();
    console.log("Finally should have been executed");
    expect(requestHasCompleted).toHaveBeenCalled();
  });
});

Output is:

# Finally should have been executed
# Finally
# expect spy requestHasCompleted to have been called

So the finally is called after the subscribe(next) is executed, which makes sense. Putting the expectation in completed: subscribe(next, error, completed), also doesn't help.

like image 440
Rafael Emshoff Avatar asked Mar 15 '26 20:03

Rafael Emshoff


1 Answers

Lol, autocomplete gave me the answer. On a whim I just put a .after the subscribe() to see if there is any handler for what happens after a subscription, and got the following suggestions: .add, .closed, .remove, .unsubscribe.

.add(function) Adds a tear down to be called during the unsubscribe() of this subscription.

To take the example from this question.

/// code
  source
    .finally(() => console.log('Finally callback'))
    .subscribe(value => console.log('#1 Next:', value), error => console.log('#1 Error:', error), () => console.log('#1 Complete'))
    .add(() => {
      console.log('Executed after finally is called');
    });

/// output
# ...
# Finally calllback
# Executed after finally is called

Although I don't quite understand what triggers the unsubscribe() (http://reactivex.io/rxjs/class/es6/Subscription.js~Subscription.html). I always thought that subscriptions just lie around until they are explicitly unsubscribed from...

like image 136
Rafael Emshoff Avatar answered Mar 17 '26 09:03

Rafael Emshoff