所以我有一个具有以下功能的基类:
public handleError(){
//some code
}
现在我正在为我的组件编写测试用例,由于某些事件链,它实际上经历了上述方法并返回错误。
如何重写/存根此方法?
我尝试了
stub()
和callFake
来尝试劫持此方法,但执行仍然通过基类中定义的方法:
it('Should call super ngOnInit()', async () => {
const { instance } = await shallow.render();
spyOn(instance, 'handleError').and.callFake(()=>{
return "error"
});
//spyOn(service, 'myMethod').and.stub();
const SuperNgOnInitSpy = spyOnSuper(ListBase, 'ngOnInit');
instance.ngOnInit();
expect(SuperNgOnInitSpy).toHaveBeenCalled();
});
无法检查继承的方法是否被执行(使用上面的方法),因为继承的方法是应用到类上的,而只需测试函数``是否被调用,这会节省你很多时间!请尝试以下代码!
it('Should call super ngOnInit()', async () => {
const { instance } = await shallow.render();
spyOn(instance, 'handleError').and.callFake(()=>{
return "error"
});
instance.ngOnInit();
expect(instance.handleError).toHaveBeenCalled();
});