From Jest notes: Note: By default, jest.spyOn also calls the spied method.
In my Angular component.
ngAfterViewInit(): void {
this.offsetPopoverPosition();
}
In my spec:
it('ngAfterViewInit() method should call offsetPopoverPosition() method', () => {
const mockListener = jest.spyOn(cmp, 'offsetPopoverPosition');
const spy = mockListener.mockImplementation(() => {
console.log('in the mock');
});
cmp.ngAfterViewInit();
expect(spy).toHaveBeenCalled();
});
Simple. Yet the original function is still being called. I checked Jest 23.x docs: https://jestjs.io/docs/en/23.x/jest-object#jestspyonobject-methodname https://jestjs.io/docs/en/23.x/mock-function-api#mockfnmockimplementationfn
And few examples on the internets but I can't prevent jest from calling the original offsetPopoverPosition()
method.
Any ideas?
I am cross linking to Jest github issue which is for some reason closed without resolving it.
Jest spyOn() calls the actual function instead of the mocked
offsetPopoverPosition
bound tothis
in the component constructor?cmp
is an instance so it wouldn't make a difference anyway. From what I can see of your code it looks like it should work. (The reason why JonathanHolvey's code in the github link doesn't work is becauseprocessVisit
is callingsaveVisit
directly so mocking the module export forsaveVisit
doesn't have any effect...that doesn't apply to your code since both of your functions are class methods from what I can see)