Volnos
Volnos

Reputation: 41

How to write unit test for subscribe method?

I'm writing unit test for the first time trying to cover this subscribe part, which keeps getting errors that I cannot figure out how to solve this.
What should be done to covering this subscribe part?

enter image description here

ts

triggerConfirmationErrorCheck(
    upgradeRequestPayload: UpgradeRequestInfoPayload,
    tripInsuranceSelectedValue: boolean
  ) {
    this.paymentMediatorService.confirmationErrorCheck$
      .pipe()
      .subscribe((data) => {
        if (this.isSuccess(data)) {
          this.invokeConfirmation(
            upgradeRequestPayload,
            tripInsuranceSelectedValue
          );
        } else if (this.isError(data)) {
          const errors = data?.validationErrorsArr?.length || 0;
          this.confirmationError.showUIError(
            errors,
            'id_paymentCardNum_creditDebit'
          );
        }
      });

This is what my spec looks like this

    it('should test triggerConfirmationErrorCheck', () => {
      const upgradeRequestPayload: UpgradeRequestInfoPayload = {
        comfortRequest: '',
        firstClassRequest: '',
        savePreferences: '',
        tripInsuranceSelectedValue: false
      };
      const tripInsuranceSelectedValue = false;
      expect(
        service.triggerConfirmationErrorCheck(
          upgradeRequestPayload,
          tripInsuranceSelectedValue
        )
      ).toBe(undefined);
    });

Any help would be appreciated!

Upvotes: 0

Views: 1197

Answers (1)

Caio Oliveira
Caio Oliveira

Reputation: 814

You can spy on the service and mock its response to be the desired observable:

//...
let myService = TestBed.inject(PaymentMediatorService);
spyOn(myService, 'confirmationErrorCheck$').and.returnValue(of(valueYouWant))

//...

Upvotes: 2

Related Questions