在Angular中的onInit()内写入订阅单元测试

时间:2018-03-27 16:17:30

标签: angular unit-testing karma-jasmine

我有一个Spinner Component类,如下所示,它将使用Angular材质显示/隐藏Progress Spinner。

export class SpinnerComponent implements OnInit, OnDestroy {
    visible = true;
    private subscription: Subscription;

    constructor(private spinnerService: SpinnerService) {}

    ngOnInit() {
         this.subscription = this.spinnerService.spinnerState.subscribe((state: SpinnerState) => {
                this.visible = state.show;
           });
     }
    ngOnDestroy() {
         if (this.subscription) {
            this.subscription.unsubscribe();
         }
    }
}

如何编写一个可以测试下面显示的特定行的规范,该行在ngOnInit()方法中?

this.visible = state.show;

1 个答案:

答案 0 :(得分:1)

第一个解决方案:

class FakeSpinnerService {
  private spinnerStateSource = new Subject();
  spinnerState = this.spinnerStateSource.asObservable();

  emit(val: boolean) {
    this.spinnerStateSource.next({ show: val });
  }
}

it('should set component.visible based on spinnerService state', () => {
  const fakeService = new FakeSpinnerService();
  const component = new SpinnerComponent(fakeService as any);

  // initial value
  expect(component.visible).toBe(true);

  component.ngOnInit();

  fakeService.emit(false);
  expect(component.visible).toBe(false);

  fakeService.emit(true);
  expect(component.visible).toBe(true);
});

需要注意的重要一点是,我们提供了旋转器服务的模拟实现。

第二个解决方案:

另一种测试方法是创建一个浅层测试,而根本不使用Angular测试实用程序。由于您不关心模板交互,因此您也可以像测试常规ts类一样测试它。

{{1}}