如何在Jasmine中测试ngOnInit的代码逻辑和Angular

How to test the code logic of ngOnInit in Jasmine and Angular

我的组件在 ngOnInit 中查找 route 中是否存在参数。如果参数不存在,则显示错误。我想测试这个逻辑。

ngOnInit() {
    this.id = this.route.snapshot.paramMap.get("id");
    if(this.id != null) {
...    } else{
      console.log("didn't get id from the route");
      this.showDialog(...);
    }
  }

我写了以下规范。在规范中,参数未在 route

中传递
 beforeEach(async() => {

    fixture = TestBed.createComponent(QuestionDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

fit('should show error if question details of a question can\'t be retrieved', () => {
    spyOn(component,'showDialog');
    expect(componetn.showDialog).toHaveBeenCalled();
  });

但是我的测试用例失败了,原因是 Expected spy showDialog to have been called

我想问题是在调用 it 之前创建组件时调用 showDialog

如何测试 ngOnInit 中的逻辑?我需要组件才能对其进行测试(即调用 it),并且我想测试在创建组件时执行的逻辑。

要测试ngOnInit方法,你只需要调用它:

component.ngOnInit();

并且路由值可以被窥探:

spyOn(component.route.snapshot.paramMap,"get").and.returnValue("some_id");

此外,您还可以更改返回值。例如:

fit("should ...", () => {
  let mock_id = null;
  spyOn(component,"showDialog");

  spyOn(component.route.snapshot.paramMap,"get").and.callFake(() => {
      return mock_id;
  });

  component.ngOnInit();
  expect(componetn.showDialog).toHaveBeenCalled();
  expect(componetn.showDialog).toHaveBeenCalledTimes(1);

  mock_id = "some_value";
  component.ngOnInit();
  expect(...).to..
  ...
  expect(componetn.showDialog).toHaveBeenCalledTimes(1);

  mock_id = "another_value";
  component.ngOnInit();
  expect(...).to..
  ...
  expect(componetn.showDialog).toHaveBeenCalledTimes(1);
});