使用核心注入器进行Angular2 2.0.1组件单元测试

时间:2016-11-04 14:43:46

标签: unit-testing angular

我使用ComponentFactoryResolver动态创建组件,并使用ReflectiveInjector动态传递它们。

这看起来像

@ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;
let inputProviders = [{
    provide: 'injectedInput',
    useValue: inputValue
}];
let resolvedInputs = ReflectiveInjector.resolve(inputProviders);
let injector = ReflectiveInjector.fromResolvedProviders(resolvedInputs, this.container.parentInjector);
let factory = componentInfo.factory.resolveComponentFactory(componentInfo.component);
let component = factory.create(injector);
this.container.insert(component.hostView);

然后动态创建的组件看起来像这样

import {Component, Injector} from '@angular/core';  
@Component({
    selector: 'mycomponent'
})
export class MyComponent {
    private id: string;

    constructor(private injector: Injector) {
        this.id = injector.get('injectedInput');
    }
}

我正在尝试为使用核心Injector模块的组件编写单元测试。我收到以下错误:

  

错误:没有injectInput的提供者!

我的spec文件如下所示:

import { MyComponent } from 'here';
describe('MyComponent', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                MyComponent
            ]
        });
    });

    let component: MyComponent;

    beforeEach(inject([RigTransferSpeedPeriodComponent], _component => {
        component = _component;
    }));

    {...my tests...}
});

我尝试了很多东西,到处搜索,但之前找不到任何人。

有什么想法吗?

非常感谢!

菲利普

1 个答案:

答案 0 :(得分:0)

用plnkr进行了一些实验,以你的问题为例; - )

@Component({
  selector: 'my-component',
  template: ''
})
export class TestComponent {
  constructor(
    private injector : Injector
  ) {
    injector.get('value1');
  }
}

describe('a test', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ TestComponent ],
      providers: [ TestComponent ]
    });
  });

  beforeEach(() => {
    this.injector1 = ReflectiveInjector.resolveAndCreate([
      {provide: 'value1', useValue: 5}
    ]);

  });

  it('inject value', () => {
    expect( this.injector1.get('value1') ).toBe(5);
  });

  describe('create component', () => {
    it('with untouched injector should throw error', () => {
      expect( () => TestBed.createComponent(TestComponent) ).toThrowError();
    })

    it('with manipulated injector', () => {
      let componentInjector = TestBed.get(Injector);
      componentInjector.parent = this.injector1;
      expect( TestBed.createComponent(TestComponent) ).toBeTruthy();
    })

    it('with injectors in the wrong order', () => {
      let componentInjector = TestBed.get(Injector);
      let combinedInjector = ReflectiveInjector.fromResolvedProviders(this.injector1, componentInjector);
      expect( () => combinedInjector.get(TestComponent) ).toThrowError();
    })
  });
});

http://plnkr.co/edit/PlUUtTOZq8bPLQ5WdAbE?p=preview

证明它与注射器的顺序相关