Jest.js 如何编写订阅方法的单元测试?

von4xj4u  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(211)

我第一次写单元测试试图涵盖这个订阅部分,它不断得到错误,我不知道如何解决这个问题。
应如何覆盖此订阅部分?

时间

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'
          );
        }
      });

这是我的规格

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

任何帮助都将不胜感激!

5hcedyr0

5hcedyr01#

您可以监视服务并模拟它的响应,使其成为所需的可观察对象:

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

//...

相关问题