SamuraiJack
SamuraiJack

Reputation: 5539

Angular Unit Testing: How to unit test subscription inside ngOnInIt()?

Component to be tested:

export class ComponentDetailsComponent implements OnInit {
     ngOnInit() {

            this.componentDetailsService.currentProperties.subscribe((data) => {
                this.loader.hideLoader();    
                 this.showPopup = data.showPopup;
         .....more code....
    }

Spec:

class ComponentDetailsServiceStub {
  defaultProperties ={       
    showToolbar: false,        
    showPopup: true, //show popup is set to true here       
    refresh: false,
  };

    propertiesSource = new BehaviorSubject(this.defaultProperties);
  currentProperties = this.propertiesSource.asObservable();

  setDefaultCancelClicked(){}
}


it('should set showPopup to correct value', () => {

    componentDetailsService.propertiesSource.next({         
      showToolbar: true,         
      showPopup: false, // show popup is set to false          
      refresh: false,

    }); 

    expect(subject.showPopup).toBe(true) ///this always passes

   });

Upvotes: 0

Views: 1050

Answers (1)

Rachitha B R
Rachitha B R

Reputation: 91

You don't have to write so many steps to pass as Observable.

import { of } from 'rxjs';
....

class ComponentDetailsServiceStub {
  defaultProperties ={       
    showToolbar: false,        
    showPopup: true, //show popup is set to true here       
    refresh: false,
  };
  currentProperties = of(defaultProperties); // will convert to Observable
  setDefaultCancelClicked(){}
}

And your test case can be:

it('should set showPopup to correct value', () => {
    subject.ngOnInit(); // jasmine will internally call subscribe on stub service created and return the stub value assigned.
    expect(subject.showPopup).toBe(true);
   });

Upvotes: 1

Related Questions