Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest spyOn not works

So I have a file that consists of a couple of functions. And I wrote a test for getOpeningHours.

  • The getOpeningHours use isLocationOrderAheadAvailable function
  • The isLocationOrderAheadAvailable function is not using getOpeningHours so it's not a circular dep issue
  • Both getOpeningHours and isLocationOrderAheadAvailable are exported functions
  • Both functions came from same file.
import * as locationUtils from './location';
import {
    isLocationOrderAheadAvailable,
    getProductItemsFromMenu,
    resolveOpeningHours,
    getOpenedTimeRanges,
    getOpeningHours,
} from './location';


describe('getOpeningHours', () => {
        it('should return same locationHours if isLocationOrderAheadAvailable is false', () => {
            jest.spyOn(locationUtils, 'isLocationOrderAheadAvailable').mockImplementation(
                jest.fn().mockReturnValue(false)
            );

            const openingHours = getOpeningHours(validLocationEntry);
            expect(openingHours).toEqual(locationHours);
        });
});

So eventually the isLocationOrderAheadAvailable not been mocked at all. The wired thing is that I did exactly the same in a different test and it worked.

Sorry, I can't give a working example of this.

like image 783
David Nazaryan Avatar asked Dec 17 '25 21:12

David Nazaryan


1 Answers

Changing from export function isLocationOrderAheadAvailable(...) to export const isLocationOrderAheadAvailable = (...): => makes jest.spyOn work.

But I still don't understand why. I think it might be connected with JS hoisting but I don't know how jest interacts with it.

like image 173
David Nazaryan Avatar answered Dec 20 '25 13:12

David Nazaryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!