Jest - when using spyOn function ensure the spied one is not called

Discussão em 'Angular' iniciado por codeepic, Janeiro 4, 2025.

  1. codeepic

    codeepic Guest

    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

    Continue reading...

Compartilhe esta Página