Angular2, testing and resolved data: how to test ngOnINit?

有些话、适合烂在心里 提交于 2019-12-22 02:51:10

问题


I'm working through the Angular2 testing guide and wish to write a test for the ngOnInit() function. The one from the Routing part 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. The examples available to me assume that an embedded OrgService can be replaced by a 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?

Thanks,

Jerome.


回答1:


What is the behavior or the ngOnInit method? All it does is assign the value of the org when the route data is resolved. 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()
  route.data = Observable.of(org)

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



回答2:


I was trying to test ngOnInit() for a component, and unfortunately the accepted answer didn't work for me. 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
  });
});


来源:https://stackoverflow.com/questions/42656045/angular2-testing-and-resolved-data-how-to-test-ngoninit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!