本文介绍了角2.0.0-rc.1 +业力:提供RouteSegment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
向组件注入RouteSegment时,仅在测试中提供RouteSegment是不够的:
When a component is injected with RouteSegment, just providing the RouteSegment in the test is not enough:
component.ts:
component.ts:
export class ComponentToTest {
private param: string;
constructor(routeSegment: RouteSegment) {
this.param = routeSegment.getParam('param');
this.getData();
}
}
component.spec.ts:
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参数.
I have no idea on how to provide the RouteSegment parameters.
推荐答案
解决方案1
不是为我工作,还是不确定为什么.
Didn't work for me, still not sure why.
RouteSegment的模拟实现:
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(RouteSegment, { useValue: new MockRouteSegment({ 'key': 'value' }) })
这篇关于角2.0.0-rc.1 +业力:提供RouteSegment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!