Javascript 角度2-模拟试验路线图

Javascript 角度2-模拟试验路线图,javascript,unit-testing,typescript,angular,angular2-routing,Javascript,Unit Testing,Typescript,Angular,Angular2 Routing,在Angular2组件的测试中,为RouteParams依赖注入模拟时遇到了一些问题。我的总体想法是,我可能会错过一些供应商 测试失败的原因有: Cannot resolve all parameters for 'RouteParams'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'RouteParams' is decorate

在Angular2组件的测试中,为RouteParams依赖注入模拟时遇到了一些问题。我的总体想法是,我可能会错过一些供应商

测试失败的原因有:

Cannot resolve all parameters for 'RouteParams'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'RouteParams' is decorated with Injectable.
我自己设法解决了这个问题,您模拟RouteProvider,为在这里着陆的人使用,即使他们与Angular4一起工作

provide(RouteParams, { useValue: new RouteParams({ id: '1' }) }) 我只是继续做了一个模拟。我想诀窍是模拟
ActivatedRoute
您需要的部分。对我来说,这样做了:

import {ActivatedRoute, ParamMap} from '@angular/router';

/**
 * Mocking the ActivatedRoute which is injected in the Component on creation.
 * This allows for easier testing as values can be set as needed.
 */
class MockActivatedRoute {
   paramMap = Observable.of(new Params());
}

/**
 * Bare bones implementation of ParamMap used in mock. Further tests can expand
 * on this implementation as needed.
 */
class Params implements ParamMap {
  keys: string[];

  private routes: {[key: string]: string|null} = {
    subject: 'foo',
    time: 'd-123-1',
    device: 'all',
    location: 'c-123'
  };

  constructor() {
    this.keys = Object.keys(this.routes);
  }

  has(name: string): boolean {
    throw new Error('Method not implemented.');
  }
  get(name: string): string|null {
    return this.routes[name];
  }
  getAll(name: string): string[] {
    throw new Error('Method not implemented.');
  }
}
然后确保在您的测试模块中,您通过real
ActivatedRoute
提供模拟服务:

providers: [
  {
    provide: ActivatedRoute,
    useValue: new MockActivatedRoute(),
  }
]
为了完成测试,我在测试的组件中使用它的方式如下:

ngOnInit() {
  this.route.paramMap
      .map((params: ParamMap) => params.get('subject') as string)
      .subscribe((subject: string) => this.subject = subject);
}