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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With