Angular2,测试和解析数据:如何测试 ngOnInit?

Angular2, testing and resolved data: How to test ngOnInit?

我正在研究 Angular2 testing guide and wish to write a test for the ngOnInit() function. The one from the Routing section of the programming guide 具有这种格式:

let org: Org = null;

ngOnInit(): void {
  let that = this;

  this.route.data
    .subscribe((data: { org: Org }) => {
      that.org = data.org;
    });
}

这是通过解析器实现的,例如:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Org> {
  let id = this.authService.user.orgId;

  return this.orgService
    .getOrg(id)
    .map(
      (org: Org) : Org => {

        if(org) {
          return org;
        } else { 
          // If  the Org isn't available then the edit page isn't appropriate.
          this.router.navigate(['/provider/home']);
          return null;
        }
     })
    .first();
}

代码工作正常,但我不确定如何为 ngOnInit 编写测试。我可用的示例假设嵌入的 OrgService 可以替换为 MockOrgService。但是,我只有一个解析器。

我最终会弄清楚如何自行测试解析器。我可以使用基于解析器的 ngOnInit 进行任何有用的测试吗?

行为或 ngOnInit 方法是什么?它所做的只是在解析路由数据时分配 org 的值。这就是您真正需要测试的全部内容。

let routeStub;

beforeEach(() => {
  routeStub = {
    data: null
  }

  TestBed.configureTestingModule({
    providers: [
      { provide: ActivatedRoute, useValue: routeStub }  
    ]
  })
})

it('should assign org when route is resolved', async(() => {
  let org = new Org()
  routeStub.data = Observable.of(org)

  fixture.detectChanges();
  fixture.whenStable().then(() => {
    expect(component.org).toEqual(org)
  })
}))

我正在尝试为一个组件测试 ngOnInit() ,不幸的是,接受的答案对我不起作用。然而,这样做了:

describe('your test', () => {
  beforeEach(async() => {
    // set up your component as necessary

    component.ngOnInit();

    await fixture.whenStable();
  });

  it('should verify your test', () => {
    // run your expectation
  });
});