如何将@viewChildren中使用的组件替换为测试double?

use*_*323 5 angular2-directives angular2-testing angular

假设我有一个我想要测试的组件,它使用了一个非常复杂的组件.此外,它使用获得的引用调用它的一些方法@viewChildren.例如

    @Component({
        moduleId: module.id,
        selector: 'test',
        template: '<complex *ngFor='let v of vals'></complex>' ,
    })
    export class TestComponent{
    vals = [1,2,3,4]
    @ViewChildren(ComplexComponent) cpxs : QueryList<ComplexComponent>
    // ....
    }
Run Code Online (Sandbox Code Playgroud)

如何在`TestBed'中替换复合组件以获得测试双?

就像是

@Component({
  moduleId : module.id,
  selector: 'complex', template: ''
})
class ComplexComponentStub {
}

describe('TestComponent', () => {
  beforeEach( async(() => {
    TestBed.configureTestingModule({
      declarations : [ComplexComponentStub, TestComponent],
    });
it('should have four sons',()=>{
   let fixture = TestBed.createComponent(TestComponent);
   let comp    = fixture.componentInstance as TestComponent;
   fixture.detectChanges();
   expect(comp.cpxs.length).toBe(4);
});

    //....
}));
Run Code Online (Sandbox Code Playgroud)

有关完整示例,请参阅plnkr http://plnkr.co/edit/ybdrN8VimzktiDCTvhwe?p=preview

yur*_*zui 4

您可以使用反射元数据功能来使其正常工作:

it('should have four sons', () => {
   const propMetadata = Reflect['getMetadata']('propMetadata', FatherComponent);
   var originType = propMetadata.cpxs[0].selector;
   propMetadata.cpxs[0].selector = ComplexComponentStub; // Replace ViewChild Type

   let fixture = TestBed.createComponent(FatherComponent);

   let comp = fixture.componentInstance as FatherComponent;
   fixture.detectChanges();
   expect(comp.cpxs.length).toBe(4);

   propMetadata.cpxs[0].selector = originType; // reset ViewChild
});
Run Code Online (Sandbox Code Playgroud)

在 Plunker 中测试

您可以在此处阅读有关装饰器和反射元数据的更多信息: