pre*_*fly 2 angular2-di angular
假设我有一个类Foo为其所有派生类提供依赖注入服务,如下所示:
export class Foo {
protected fb : FormBuilder;
protected router : Router;
protected otherService : OtherService;
protected anotherService : AnotherService;
constructor(injector : Injector) {
this.fb = injector.get(FormBuilder);
this.router = injector.get(Router);
this.otherService = injector.get(OtherService);
this.anotherService = injector.get(AnotherService);
}
Run Code Online (Sandbox Code Playgroud)
它具有从它派生的类:
export class Bar extends Foo {
constructor(injector : Injector){
super(injector);
}
}
Run Code Online (Sandbox Code Playgroud)
如何正确地对父类进行单元测试,而不会遇到:
Error: Can't resolve all parameters for Foo: (?)
目前我已经(尝试了很多很多不同的东西来让它工作,但失败了:()
export function main() {
describe('Class: Foo', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
Foo,
Injector,
OtherService,
AnotherService
]
});
}));
it('should compile', inject([Foo, Injector], ( foo: Foo, injector : Injector ) => {
console.log("INJECTOR", injector);
expect(foo).toBeTruthy();
}));
});
}
Run Code Online (Sandbox Code Playgroud)
我也试过这样使用ReflectiveInjector.resolveAndCreate:
{
provide : Injector,
useValue: ReflectiveInjector.resolveAndCreate([FormBuilder, Router, OtherService, AnotherService])
}
Run Code Online (Sandbox Code Playgroud)
但仍然没有骰子:(有什么想法吗?
似乎您需要在构造函数中添加@Inject装饰器InjectorFoo
constructor(@Inject(Injector) injector: Injector) {
Run Code Online (Sandbox Code Playgroud)
并TestBed正确配置。更准确地说,您必须导入,RouterModule否则您将遇到另一个问题Router:
TestBed.configureTestingModule({
imports: [
RouterModule.forRoot([])
],
providers: [
FormBuilder,
Foo,
OtherService,
AnotherService
]
});
Run Code Online (Sandbox Code Playgroud)
你可以在Plunker Example 中尝试它
| 归档时间: |
|
| 查看次数: |
3466 次 |
| 最近记录: |