本文介绍了angular 2.0.0-rc.1 + karma:提供 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'(?, ?, ?, ?,?).确保所有参数都用 Inject 或具有有效的类型注释并且RouteSegment"装饰有可注射.

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

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

推荐答案

解决方案 1

看 HomeBrew 的回答

对我不起作用,仍然不知道为什么.

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

这篇关于angular 2.0.0-rc.1 + karma:提供 RouteSegment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 08:56