3

假设我有一个类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);
}

它具有从它派生的类:

export class Bar extends Foo {

    constructor(injector : Injector){
         super(injector);
    }
}

如何正确地对父类进行单元测试,而不会遇到:

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();
        }));

    });
}

我也尝试过ReflectiveInjector.resolveAndCreate这样使用:

{
    provide : Injector,
    useValue: ReflectiveInjector.resolveAndCreate([FormBuilder, Router, OtherService, AnotherService])
}

但仍然没有骰子:(有什么想法吗?

4

1 回答 1

5

似乎您需要在构造函数中添加@Inject装饰器InjectorFoo

constructor(@Inject(Injector) injector: Injector) {

TestBed正确配置。更准确地说,您必须导入,RouterModule否则您将遇到另一个问题Router

TestBed.configureTestingModule({
  imports: [
    RouterModule.forRoot([])
  ],
  providers: [    
    FormBuilder,
    Foo,
    OtherService,
    AnotherService
  ]
});

你可以在Plunker Example中尝试一下

于 2017-03-20T15:41:15.827 回答