加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 如何替换@viewChildren中用于测试double的组件?

发布时间:2020-12-17 17:35:58 所属栏目:安全 来源:网络整理
导读:假设我有一个我想要测试的组件,它使用了一个非常复杂的组件.此外,它使用@viewChildren获得的引用调用它的一些方法.例如 @Component({ moduleId: module.id,selector: 'test',template: 'complex *ngFor='let v of vals'/complex',}) export class TestCompon
假设我有一个我想要测试的组件,它使用了一个非常复杂的组件.此外,它使用@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>
    // ....
    }

如何在`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);
});

    //....
}));

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

解决方法

您可以使用反射元数据功能来执行此操作:

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

Test in Plunker

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

> Angular 2,decorators and class inheritance

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读