【问题标题】:Angular2, testing and resolved data: How to test ngOnInit?Angular2,测试和解析数据:如何测试 ngOnInit?
【发布时间】:2017-07-28 02:50:37
【问题描述】:

我正在处理Angular2 testing guide 并希望为ngOnInit() 函数编写一个测试。来自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 应该是 Angular 团队的责任,你应该只需要测试你从中调用的方法
  • 嗨。你是如何单独对 Resolve 类进行单元测试的?我正在寻找这样做,只是想知道您的解决方案是什么

标签: javascript angular jasmine karma-runner resolver


【解决方案1】:

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

【讨论】:

  • 热门!那是你第三次救了我,因为你也不知不觉又答了一个Q。那就是:我如何摆脱“没有激活路由的提供者!”错误。谢谢,杰罗姆。
  • async() (it() 的第二个参数) 如果测试主体进行 XHR 调用,则应使用,否则使用 fakeAsync:angular.io/guide/testing#async-test-with-async
  • fixture.whenStable() 拯救了我的一天!
  • 您能否帮助我解决由于在 ngOnInit() 中使用路由参数而导致单元测试失败的问题。这是堆栈链接:stackoverflow.com/questions/64345423/…
  • @Paul,您能帮我解决我遇到的类似问题吗? stackoverflow.com/questions/64345423/…
【解决方案2】:

我试图测试 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
  });
});

【讨论】:

  • 通常我们会使用 TestBed.createComponent(...) 来获取我认为调用 ngOnInit 的组件。我们最终不会调用两次 ngOnInit 吗?
  • 没有必要调用“component.ngOnInit()”,除非您的单元测试在“beforeEach”函数调用之外创建了一个新对象。
  • @Ken 这不是我在项目中看到的行为。我可以通过将一个间谍附加到 ngOnInit 来验证这一点,然后等待一个稳定的夹具。
猜你喜欢
  • 2016-08-09
  • 2019-02-18
  • 1970-01-01
  • 2012-08-08
  • 2017-03-09
  • 2020-08-08
  • 2017-09-04
  • 1970-01-01
  • 2017-03-30
相关资源
最近更新 更多