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 destroyed.

it('should call the unsubscribe method on the jobCompleted Subscription within ngOnDestroy', () => {
  let jobListenerServiceMock = TestBed.inject(JobListenerService);        

  //The jobCompleted() method returns an Observable.
  //Subject is a kind of Observable, and gives us an observed property.
  const fakeObservable = new Subject<Job>();
  jobListenerServiceMock.jobCompleted =
    jasmine.createSpy('jobCompleted').and.returnValue(fakeObservable);

  fixture.detectChanges();
  expect(fakeObservable.observed).toBeTrue(); //Make sure we have observers      
  component.ngOnDestroy();        
 
  expect(fakeObservable.observed).toBeFalse(); //Make sure we no longer have observers
});

Comments

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4

How to Determine if a Column Exists in a DataReader