简体   繁体   English

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

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

I'm working through the Angular2 testing guide and wish to write a test for the ngOnInit() function.我正在阅读Angular2 测试指南,并希望为ngOnInit()函数编写一个测试。 The one from the Routing section of the programming guide has this format:编程指南中路由部分的格式如下:

let org: Org = null;

ngOnInit(): void {
  let that = this;

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

This is fulfilled through a resolver, like:这是通过解析器实现的,例如:

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

The code works OK, but I'm not sure how to write a test for ngOnInit .代码工作正常,但我不确定如何为ngOnInit编写测试。 The examples available to me assume that an embedded OrgService can be replaced by a MockOrgService .我可以使用的示例假设嵌入式OrgService可以替换为MockOrgService However, all I have is a resolver.但是,我只有一个解析器。

I'll eventually figure out how to test the resolver on its own.我最终会弄清楚如何自己测试解析器。 Are there any useful tests I can do with a resolver-based ngOnInit ?我可以使用基于解析器的ngOnInit任何有用的测试吗?

What is the behavior or the ngOnInit method?什么是行为或ngOnInit方法? All it does is assign the value of the org when the route data is resolved.它所做的就是在解析路由数据时分配org的值。 So that's all you really need to test.所以这就是你真正需要测试的。

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

I was trying to test ngOnInit() for a component, and unfortunately the accepted answer didn't work for me.我试图为一个组件测试 ngOnInit(),不幸的是,接受的答案对我不起作用。 However, this did:然而,这确实:

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

    component.ngOnInit();

    await fixture.whenStable();
  });

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM