[英]Angular ngOnInit never executed when creating component inside ngFor
[英]How to override a function inside ngOnInit in jasmine when creating an angular component in TestBed?
我有一个 ngOnInit 函数,它在同一个组件内调用另一个函数,我正在使用 jasmine 测试测试这个组件。
我想模拟 ngOnInit 函数内部的函数,以防止执行原始实现。
ngOnInit(): void {
this.initializeData();
}
我在每个函数之前尝试了以下实现,但这样 ngOninit 将执行两次:
beforeEach(() => {
testHostFixture = TestBed.createComponent(TestHostComponent);
testHostComponent = testHostFixture.componentInstance;
spyOn(testHostComponent, 'initializeData').and.callFake(()=>{console.log("replacement");});
testHostComponent.ngOnInit();
testHostFixture.detectChanges();
});
在 ngOnInit 第一次执行之前,有没有模拟函数“initializeData”的实现?
谢谢。
您需要在创建组件之前进行监视。 因此,只需将间谍移动到创建线上方即可。
beforeEach(() => {
spyOn(testHostComponent, 'initializeData').and.callFake(()=>
{console.log("replacement");});
testHostFixture = TestBed.createComponent(TestHostComponent);
testHostComponent = testHostFixture.componentInstance;
testHostComponent.ngOnInit();
testHostFixture.detectChanges();
});
你ngOnInit()
将被调用两次在这里作为组件运行ngOnInit()
时,它在创建TestBed
。 如果你只希望它被调用一次。 删除显式调用testHostComponent.ngOnInit();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.