How to Verify Observables are Unsubscribed to in Angular Unit Tests
In most cases, when you subscribe to an Observable , you should also unsubscribe from it. In Angular, there are a few exceptions (for example, Observables returned by HttpClient ), but usually unsubscribing is the way to go. But how would you write a unit test to make sure this happens? One way is by using a Subject . A Subject is a kind of Observable. It includes an observed property which is a boolean and indicates whether or not it is being subscribed to. Prior to this, there was an observers property which provided a count of observers, but this has been deprecated. In the test below, the component being tested contains code to ensure that JobListenerService.jobCompleted Observable is being unsubscribed to when the component's ngOnDestroy() method is called. The mock of the service returns a Subject (a type of Observable), and we use that Subject to verify that it's being observed before the component is destroyed, but no longer being observed after the component is