Angular testing how to prevent ngOnInit call to test a method directly

前端 未结 3 1772
天命终不由人
天命终不由人 2020-12-24 02:35

Context

I have a component. Inside of it, the ngOnInit function calls another function of component to retrieve user List. I want to make two series of tets:

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-24 03:06

    it(`should get the user List via refresh function`, fakeAsync(() => {
      let ngOnInitFn = UserListComponent.prototype.ngOnInit;
      UserListComponent.prototype.ngOnInit = () => {} // override ngOnInit
      comp.onRefreshUserList();
      tick();
    
      fixture.detectChanges(); 
      UserListComponent.prototype.ngOnInit = ngOnInitFn; // revert ngOnInit
    
      expect(comp.userList.length).toBe(3, 'user list after function call');
    }));
    

    Plunker Example

提交回复
热议问题