I'm currently in the process of testing a file that exports a single default function and also needs to create an object prior to exporting the function. It's crucial for this object to remain constant and be the same instance every time the exported function is invoked.
Below is a simplified version of the module:
import { HttpClient } from '../client'
const client = new HttpClient()
export default (params) => {
const url = 'www.'
// Additional code here to generate URL based on passed params
return client.get(url)
}
The objective is to verify that the URL sent to the client.get() function is accurate, which brings us to the test case below:
import myModule from '../myModule'
import { HttpClient } from '../client'
jest.mock('../client')
const mockHttpClient = { get: jest.fn(() => 'test') }
HttpClient.mockImplementation(() => mockHttpClient)
it('should parse the query param string', () => {
console.log(myModule({}))
})
During test execution, the response from myModule({})
consistently comes back as undefined.
However, if I relocate the const client = new HttpClient()
line within the exported function itself, everything functions correctly, and myModule({})
returns test
.
It's imperative for the HttpClient to only be instantiated once and maintain the same instance upon each function call, emphasizing the need for it to be created outside the function. Is there a way to mock this object creation process to return my desired value? Your assistance is greatly appreciated.