angular 2.0.0-rc.1 + karma: provide RouteSegment

∥☆過路亽.° 提交于 2019-12-22 09:51:05

问题


When a component is injected with RouteSegment, just providing the RouteSegment in the test is not enough:

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

Following error will occur:

Error: Cannot resolve all parameters for 'RouteSegment'(?, ?, ?, ?, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'RouteSegment' is decorated with Injectable.

I have no idea on how to provide the RouteSegment parameters.


回答1:


I had the same issue, I had to look at the angular router code and the specs they have in there repo. You should be able to provide the routeSegment like this:

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

or you can just mock out a new RouteSegment similar to how you did with RouteParams:

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

Is now this:

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

To create it you just have to pass it a couple of extra parameters.




回答2:


Solution 1

See the answer of HomeBrew

Didn't work for me, still not sure why.

Solution 2

A mock implementation of 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 it like this:

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


来源:https://stackoverflow.com/questions/37147812/angular-2-0-0-rc-1-karma-provide-routesegment

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