How to mock/override a method defined in base class in angular

43 views Asked by At

So I have a base class that has a following function:

public handleError(){
 //some code
}

Now I'm writing test case for my child component that inherits it and due to some chain of event it actually goes through the above method and returns an error.

How can I override/stub this method?

I tried stub() and callFake to try to hijack this method but the execution still passes though the one defined in base class:

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

There are 1 answers

3
Naren Murali On

Its not possible to check if the inherited method is executed or not (by using the above method), since the inherited methods are applied to the class, instead just test if the method handleError has been called, this will save you a lot of time! please try the below code!

it('Should call super ngOnInit()', async () => {
  const { instance } = await shallow.render();
  spyOn(instance, 'handleError').and.callFake(()=>{
    return "error"
  });
  instance.ngOnInit();    
  expect(instance.handleError).toHaveBeenCalled();
});