首页 > 解决方案 > 如何为行为主题编写单元测试

问题描述

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

有人可以告诉我如何为此编写单元测试用例..吗?这是我写的,但它说“失败:无法读取未定义的属性'订阅'”

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

标签: angularunit-testingkarma-jasminekarma-runnerjasmine-node

解决方案


试试这个:

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([]);
});

推荐阅读