gpt4 book ai didi

unit-testing - 使用核心注入(inject)器的 Angular2 2.0.1 组件单元测试

转载 作者:太空狗 更新时间:2023-10-29 17:28:58 24 4
gpt4 key购买 nike

我正在使用 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 模块的组件编写单元测试。我收到以下错误:

Error: No provider for injectedInput!

我的规范文件如下所示:

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

let component: MyComponent;

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

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

我尝试了很多东西并到处搜索,但找不到以前这样做的人。

有什么想法吗?

非常感谢!

菲利普

最佳答案

用 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

证明这是关于注入(inject)器的顺序

关于unit-testing - 使用核心注入(inject)器的 Angular2 2.0.1 组件单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40425488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com