gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:36:06 29 4
gpt4 key购买 nike

假设我有一个要测试的组件,它使用了一个非常复杂的组件。此外,它使用通过 @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

最佳答案

您可以使用 reflect-metadata 功能使其正常工作:

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 - 如何替换@viewChildren 中用于测试替身的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40855910/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com