4

I'm trying to write a unit test for a function that calls some helper functions in the same file. I'm using jest.spyOn to mock away those helper functions as it appears that it can do that.

myModule.js

export const getUserName = () => {
    return "mjordan"
}

export const getItem = () => {
    return 'basketball'
}

export const getUserWithItem = () => {
    const userName = getUserName()
    const item = getItem()
    
    return userName + " " + item
} 

myModule.test.js

import * as myModule from 'path/to/module'

describe('getUserWithItem', () => {
    beforeEach(() => {
        jest.restoreAllMocks()
    })

    it('Returns user with item', () => {
        jest.spyOn(myModule, 'getUserName').mockImplementation(() => 'tigerwoods')
        jest.spyOn(myModule, 'getItem').mockImplementation(() => 'golf ball')

        const result = myModule.getUserWithItem()

        expect(result).toEqual("tigerwoods golf ball")
    })
})

However, the jest.spyOn function does not appear to be mocking the implementation of the spied on functions but the test is calling the original functions instead which results in an output of mjordan basketball instead.

Am I missing something with how spyOn is supposed to work?

noblerare
  • 10,277
  • 23
  • 78
  • 140
  • See https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest/70066090#70066090 – jonrsharpe Aug 22 '22 at 20:27
  • The framework offers the ability to mock and restore the mock in the same suite. It should be possible. – Kraken Jan 20 '23 at 12:32

1 Answers1

1

The easiest way I have found to do what you want is to explicitly call the exported version of the function in your module, i.e.

export const getUserName = () => {
    return "mjordan"
}

export const getItem = () => {
    return 'basketball'
}

export const getUserWithItem = () => {
    const userName = exports.getUserName()
    const item = exports.getItem()
    
    return userName + " " + item
}