2017-06-15 61 views
0

我试图测试注入它的父组件作为组件:角4 +噶测试组件

constructor(@Host() app: ParentComponent) { 
 
    ... 
 
}

当我运行测试,我得到以下信息:

错误:无提供者为父级

我已经有我包括父组件和子组件中使用的所有依赖项。我是否需要做任何特定的事情来注入主机组件?

这里是我完整的测试:

describe('ChildComponent: Component',() => { 
 
\t //declare the component 
 
\t let comp: ChildComponent; 
 
\t let ca: ComponentFixture<ChildComponent>; 
 

 
\t //setup 
 
\t //first the async call to compile all the external templates 
 
\t beforeEach(async(() => { 
 
\t \t TestBed.configureTestingModule({ 
 
\t \t \t imports: [ 
 
\t \t \t \t ... 
 
\t \t \t ], 
 
\t \t \t declarations: [ 
 
\t \t \t \t ParentComponent, 
 
\t \t \t \t ChildComponent 
 
\t \t \t ], 
 
\t \t \t providers: [ 
 
\t \t \t \t ... 
 
\t \t \t ] 
 
\t \t }) 
 
\t \t .compileComponents(); 
 
\t })); 
 
\t //then the sync call to create the instance 
 
\t beforeEach(() => { 
 
\t \t 
 
\t \t ca = TestBed.createComponent(ChildComponent); 
 
\t \t comp = ca.componentInstance; 
 

 
\t \t ca.detectChanges(); 
 
\t }); 
 

 
\t afterEach(() => { 
 
\t \t comp = null; 
 
\t \t ca = null; 
 
\t }); 
 

 
\t //define the tests 
 
\t it('should have items...',() => { 
 
\t \t let count: number = comp.someArray.length; 
 
\t \t expect(count).toBeGreaterThan(0); \t \t 
 
\t }); 
 
});

回答

0

您必须指定此组件供应商。

TestBed.configureTestingModule({ 
 
\t \t \t imports: [ 
 
\t \t \t \t ... 
 
\t \t \t ], 
 
\t \t \t declarations: [ 
 
\t \t \t \t ParentComponent, 
 
\t \t \t \t ChildComponent 
 
\t \t \t ], 
 
\t \t \t providers: [ 
 
\t \t \t \t {provide: ParentComponent, useClass: ParentComponent} 
 
\t \t \t ] 
 
\t \t }) 
 
\t \t .compileComponents();