如何将@viewChildren 中使用的组件替换为测试替身? [英] How to replace a component used in @viewChildren for a test double?

查看:18
本文介绍了如何将@viewChildren 中使用的组件替换为测试替身?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a component I want to test that uses a very complex component. Furthermore it calls some of its methods using references obtained by @viewChildren. For example

    @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>
    // ....
    }

如何替换TestBed"中测试替身的复杂组件?

How can I replace the complex-component for a test double in `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);
});

    //....
}));

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

For a full example see the plnkr http://plnkr.co/edit/ybdrN8VimzktiDCTvhwe?p=preview

推荐答案

您可以使用反射元数据功能来完成它的工作:

You can use reflect-metadata features to do it working:

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

在 Plunker 中测试

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

You can read more about decorators and about reflect-metadata here:

这篇关于如何将@viewChildren 中使用的组件替换为测试替身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆