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.