angular 2.0.0-rc.1 + karma:提供RouteSegment

时间:2016-05-10 19:56:41

标签: angular angular2-routing

使用RouteSegment注入组件时,仅在测试中提供RouteSegment是不够的:

component.ts:

export class ComponentToTest {
  private param: string;

  constructor(routeSegment: RouteSegment) {
    this.param = routeSegment.getParam('param');
    this.getData();
  }
}

component.spec.ts:

import {Router, RouteSegment} from '@angular/router';

import {it, inject, beforeEachProviders} from '@angular/core/testing';
import {ROUTER_FAKE_PROVIDERS} from '@angular/router/testing';

import {ComponentToTest} from './component';

describe('ComponentToTest', () => {
  beforeEachProviders(() => [
    ROUTER_FAKE_PROVIDERS,
    RouteSegment,
    ComponentToTest
  ]);

  it('should call getData() on contruct', inject([Router], (router) => {
    spyOn(ComponentToTest.prototype, 'getData');
    expect(ComponentToTest.prototype.getData).not.toHaveBeenCalled();
    let component = new ComponentToTest(router);
    expect(ComponentToTest.prototype.getData).toHaveBeenCalled();
  }));
});

将发生以下错误:

  

错误:无法解析' RouteSegment'(?,?,?,?,   ?)。确保所有参数都使用Inject或   有有效的类型注释和那个' RouteSegment'装饰着   可注射的。

我不知道如何提供RouteSegment参数。

2 个答案:

答案 0 :(得分:2)

我有同样的问题,我不得不看看角度路由器代码和它们在那里的规格。您应该能够像这样提供routeSegment:

import {RouteSegment, Router} from '@angular/router';
provide(RouteSegment, {useFactory: (r: any) => r.routeTree.root, deps: [Router]})

或者你可以模拟一个新的RouteSegment,类似于你对RouteParams的处理方式:

provide(RouteParams, { useValue: new RouteParams({ page: 'terms-conditions' }) }),

现在是这样的:

provide(RouteSegment, { useValue: new RouteSegment([], { page: 'terms-conditions' }, null, null, null) }),

要创建它,您只需要传递几个额外的参数。

答案 1 :(得分:1)

解决方案1 ​​

See the answer of HomeBrew

对我不起作用,仍然不确定原因。

解决方案2

RouteSegment的模拟实现:

class MockRouteSegment implements RouteSegment {
  urlSegments: any;
  parameters: any;
  outlet: string;
  _type: any;
  _componentFactory: any;
  type: any;
  stringifiedUrlSegments: string;
  constructor(parameters?: { [key: string]: any; }) {
    this.parameters = parameters
  }
  getParam(param: string) {
    return this.parameters[param];
  }
}

像这样提供:

provide(RouteSegment, { useValue: new MockRouteSegment({ 'key': 'value' }) })