Search code examples
angularunit-testingkarma-jasminekarma-runnerjasmine-node

how to write unit test for behavior subject


 @Input() public openDrawer: BehaviorSubject<{
    open: boolean;
    assetConditionDetails: AssetConditionIdDetails[];
    selectedAssets: SelectedAssets[];
  }>;

 public ngOnInit(): void {
    this.openDrawer.subscribe((result) => {
      if (result) {
        this.showLoader = result.open;
        this.isDrawerActive = result.open;
        this.selectedAssets = result.selectedAssets;
        this.assetConditionDetails = result.assetConditionDetails;
      }
    });
  }

can someone please tell me how to write a unit test case for this ..? this is what I wrote but it says "Failed: Cannot read property 'subscribe' of undefined"

it('should get users', async(() => {
    component.openDrawer.subscribe(result => {
      fixture.detectChanges()
      expect(result.open).toBe(component.showLoader)
    })
  }))

Solution

  • Try this:

    it('should get users', () => {
     // mock openDrawer
      component.openDrawer = new BehaviorSubject<any>({ open: true, assetConditionDetails: [], selectedAssets: [] });
      // explicitly call ngOnInit
      component.ngOnInit();
    
      expect(component.showLoader).toBe(true);
      expect(component.isDrawerActive).toBe(true);
      expect(component.selectedAssets).toEqual([]);
      expect(component.assetConditionDetails).toEqual([]);
    });