0

I have one subscription inside my ngoninit in ts file. I want to unit test this subscription how should i can do this?

code.ts

this.generalConfigSubscription = this.generalConfigService.getGeneralConfigState().subscribe((response) => {
      if (response && response.status == 'success') {
        if (response.data && response.data) {
          this.configData = response.data;
          this.calculateNewValues = response.data.calculation_trigger ? response.data.calculation_trigger : [];
          this.valueValidity=response.data.value_validity ? response.data.value_validity : []
        }
      }
    })

generalConfigService.ts

    private initialGeneralConfigState: GeneralConfigState = undefined;
    private generalConfigStateTracker = new BehaviorSubject<GeneralConfigState>(this.initialGeneralConfigState);
                                 .
                                 .
                                 .
    /** Allows subscription to the behavior subject as an observable */
    getGeneralConfigState(): Observable<GeneralConfigState> {
        return this.generalConfigStateTracker.asObservable();
    }

1 Answers1

0

Pull the code block within the subscription into it's own function and unit test the function. This way you can skip any potential marble testing for RxJS and do it the old fashion way.

this.generalConfigSubscription = this.generalConfigService.getGeneralConfigState()
    .subscribe((response) => this.parseGeneralConfigStateResponse(response))
    
// Unit test me like any other non-subscription function
parseGeneralConfigStateResponse(response: Response) {
 if (response && response.status == 'success') {
        if (response.data && response.data) {
          this.configData = response.data;
          this.calculateNewValues = response.data.calculation_trigger ? response.data.calculation_trigger : [];
          this.valueValidity=response.data.value_validity ? response.data.value_validity : []
        }
      }
}
Esaith
  • 706
  • 9
  • 12