6

How test the call on method of private variable ? I must test the call of unsubscribe method when the ngOnDestroy is called.

There is my code

import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { LoaderService } from '@core/components/loaders/services/loader.service';

@Component({
  selector: 'loader-mask',
  templateUrl: './loader-mask.component.html',
  styleUrls: ['./loader-mask.component.css']
})

export class LoaderMaskComponent implements OnInit {

  show = false;
  private subscription: Subscription;

  constructor(private loaderService: LoaderService) { }

  ngOnInit() {
    this.subscription = this.loaderService.loaderState
      .subscribe((state: boolean) => {        
        this.show = state;
      });
  }

  ngOnDestroy() {    
    if (this.subscription)
      this.subscription.unsubscribe();
    }
}

There is my test code

it('should destroy the subscription when destroying', () => {
    const spyUnSubscribe = spyOn(component['subscription'], 'unsubscribe').and.callThrough();
    component.ngOnDestroy();  
    expect(spyUnSubscribe).toHaveBeenCalled();  
    expect(component['subscription']).toBeUndefined();
  });

There is the issue :

Error: <spyOn> : could not find an object to spy upon for unsubscribe()
Usage: spyOn(<object>, <methodName>)
3
  • You are subscribing to the service so you could mock/spy the service and control the returned observable and spy on it. Commented Jan 18, 2018 at 10:09
  • you cannot access private properties at all. that is why they are private Commented Jan 18, 2018 at 10:10
  • any answer on it? Commented Apr 15, 2020 at 12:11

2 Answers 2

3

Put any before spyOn to cheat Typescript compilator.

spyOn<any>(component['subscription'], 'unsubscribe')

Sign up to request clarification or add additional context in comments.

Comments

0

Actually something similar like this worked for me

spyOn(loginComponent['loaderSubscription'], 'unsubscribe');
loginComponent.ngOnDestroy();
expect(loginComponent['loaderSubscription'].unsubscribe).toHaveBeenCalled();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.