How to replace the component used in @viewChildren for test double?

Suppose I have a component that I want to test that uses a very complex component. In addition, he calls some of his methods using the links obtained with @viewChildren . for instance

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

How to replace a complex component for a test double in "TestBed"?

Sort of

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

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

+5
source share
1 answer

You can use reflection-metadata functions to do this:

 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

Learn more about decorators and reflection metadata here:

+4
source

Source: https://habr.com/ru/post/1260480/


All Articles