Home > other >  How to test an Observable<boolean>
How to test an Observable<boolean>

Time:09-28

I have a condition that returns an Observable like the following:

app.component.ts


  import { Observable } from "rxjs";
    
  export class ProductComponent implements OnInit

        ProductListLength: Number;
        isProductListEmpty: Observable<boolean>; 
    }
    
    ngOnInit(): void {

        if(this.ProductListLength === 0)
        this.isProductListEmpty = new Observable((observer) => observer.next(true))
    } 
        else {
        this.isProductListEmpty = new Observable((observer) => observer.next(false))
    }

I tried to run these test cases:

app.component.spec.ts


it('should return true when List is empty', () => {

   component.productListLength = 0
   fixture.detectChanges()

   expect(component.isProductListEmpty).toBeTrue()
})

it('should return false when List not empty', () => {

   component.productListLength = 2
   fixture.detectChanges()

   expect(component.isProductListEmpty).toBeFalse()
})

But running ng test I receive this: ERROR: Expected Observable({_isScalar: false, _subscribe: Function}) to be true

How to properly test these cases?

CodePudding user response:

you can make your tests async by using the argument to the tests to tell it when it's done:

it('should return true when List is empty', (done) => {

   component.productListLength = 0
   fixture.detectChanges()

   component.isProductListEmpty.subscribe(val => {
     expect(val).toBeTrue();
     done();
   });
})

CodePudding user response:

You need to get the value from the observable. You can subscribe to it or use async await. Something like the following should work (not tested).

it('should return false when List not empty', async () => {

   component.productListLength = 2
   fixture.detectChanges();
   const res = await component.isProductListEmpty.toPromise();
   expect(res).toBeFalse()
})

  • Related