Angular2,测试和解析数据:如何测试ngOnINit? [英] Angular2, testing and resolved data: how to test ngOnINit?

查看:261
本文介绍了Angular2,测试和解析数据:如何测试ngOnINit?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理 Angular2测试指南并希望为ngOnInit()函数编写测试。编程指南的Routing部分中的那个具有以下格式:

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

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

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.

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

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 方法?所有这一切都是在解析路径数据时分配 org 的值。所以你真的需要测试它。

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

这篇关于Angular2,测试和解析数据:如何测试ngOnINit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆