【问题标题】:Unit Test Angular Using Subscribe for Success Condition shows error使用订阅成功条件的单元测试角度显示错误
【发布时间】:2021-09-20 20:33:41
【问题描述】:

您好,我需要为此函数编写单元测试角度,如下所示:

  resendOTP() {
      this.authProvider.resendOTP(this.tempId, this.tempToken).subscribe((result) => {
      this.tempId = result.data.resendOtp.id;
      this.tempToken = result.data.resendOtp.access_token;
      this.showResendInfo = true;
      this.showResend = false;
      this.messageBoxService.showSuccess('SMS has been sent', 2000);
      this.startTimer();
    }, (error) => {
      if (error.graphQLErrors[0].message.includes('Maximum limit exceeded')) {
        this.validError = true;
        this.loginState = 'login';
        this.propertyAlert.message = `You\'ve requested OTP Code after the 5th attempt and your account has been
        suspended. Please contact the administrator to recover it.`;
        // setTimeout(() => {
        //   this.reloadCaptcha();
        // }, 100);
      }
    });
  }

我成功创建了错误条件

it('显示帐户在尝试 5 次 otp 后暂停', () => { spyOn(providerService, 'resendOTP').and.returnValue(throwError({ graphQLErrors: [{ message: 'Maximum limit exceeded' }] })); 组件.resendOTP(); 夹具.detectChanges(); const errorElem = fixture.debugElement.query(By.css('.alert-container')).nativeElement; 期望(component.validError).toBeTruthy(); 期望((component.propertyAlert.message).includes('suspended')).toBeTruthy(); });

但是当我创建成功条件时

it('show account success after make 5 otp attemps', () => {
  let response = [];
  spyOn(providerService, 'resendOTP').and.returnValue(of(response));
  component.resendOTP();
  expect(component.showResend).toBeFalsy()
  expect(component.showResendInfo).toBeTruthy()    
});

它显示“Observable”类型的参数是否不可分配给“Observable, Record>>”类型的参数。 类型“any[]”与类型“FetchResult, Record>”没有共同的属性。 有人知道这有什么问题吗?我已经从 rxjs 导入了 { of }。谢谢

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine


    【解决方案1】:

    它表示响应对象的类型错误。将响应的值更改为 FetchResult, Record>

    考虑在您的 resendOTP() 方法中处理订阅,因为现在您可能会引入内存泄漏。 例如。

    ngOnInit() {
      this.subscription = this.yourObservable.subscribe(() => {
       //some code
       });
    }
    
    ngOnDestroy() {
      this.subscription.unsubscribe();
    }   
    

    明确声明返回类型也是一个好习惯

     resendOTP(): void {
        //your code
      }
    

    【讨论】:

      猜你喜欢
      • 2021-10-20
      • 2020-01-15
      • 1970-01-01
      • 2019-02-25
      • 2019-08-22
      • 2018-02-01
      • 2020-03-09
      • 2018-10-03
      • 1970-01-01
      相关资源
      最近更新 更多