简体   繁体   English

Angular 中的单元测试 rxjs

[英]Unit testing rxjs in Angular

Im having a problem writing unit tests for observable in Angular... Im trying to test cases if displayPaymentsLineItem$ will be true or false depending on the values of mobileAccountBalance$, and selectedMobileDigitalBill$... Can anyone help?我在为 Angular 中的 observable 编写单元测试时遇到问题...我尝试根据 mobileAccountBalance$ 和 selectedMobileDigitalBill$ 的值来测试 displayPaymentsLineItem$ 是真还是假...有人可以帮忙吗?

  public selectedMobileDigitalBill$: Observable<MobileDigitalBill>;
  public mobileAccountBalance$: Observable<MobileAccountBalance>;

  private expandedLinesMap: object = {};
  private expandedTaxesAndFees: boolean = false;
  private devices: MobileDevice[] = [];
  private destroy$: Subject<void> = new Subject();

  constructor(]
    private mobileStatementsTabFacade: MobileStatementsTabFacade,
    private billingMobileFacade: BillingMobileFacade,
  ) {}

  ngOnInit() {
        this.mobileAccountBalance$ = this.mobileStatementsTabFacade.mobileAccountBalance$;

        this.displayPaymentsLineItem$ = combineLatest([
          this.mobileAccountBalance$,
          this.selectedMobileDigitalBill$,
        ]).pipe(
          map(([mobileAccountBalance, selectedMobileDigitalBill]: [MobileAccountBalance, MobileDigitalBill]) => {
            const isPastDue: boolean = mobileAccountBalance?.pastdue > 0;
            const hasPayments: boolean = selectedMobileDigitalBill?.payments?.length > 0;

            return isPastDue && hasPayments;
          })
        );
      }
    });

You can take(1) (take one value, then complete) and subscribe to test if the emitted value is falsy.您可以take(1) (取一个值,然后完成)并订阅以测试发出的值是否为假。 Observables need to be completed if you test them this way.如果您以这种方式测试它们,则需要完成 Observables。

describe('The display payment line items observable', () => {
  it('should emit truthy', () => {
    displayPaymentsLineItem$
    .pipe(take(1))
    .subscribe(value =>{
      expect(value).toBeTruthy();
    });
  }
}

That being said, displayPaymentsLineItem$ won't emit anything if the two observables inside combineLatest() aren't defined in your test.话虽如此,如果您的测试中未定义combineLatest()中的两个可观察对象,则displayPaymentsLineItem$不会发出任何内容。 Since they come from two facades, they may need to be provided before starting your test.由于它们来自两个方面,因此可能需要在开始测试之前提供它们。

Also, about your code example:另外,关于您的代码示例:

  1. displayPaymentsLineItem$ isn't declared before the constructor. displayPaymentsLineItem$没有在构造函数之前声明。
  2. selectedMobileDigitalBill$ is declared but is never defined before it is referenced inside combineLatest() . selectedMobileDigitalBill$已声明,但在在combineLatest()中引用之前从未定义过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM