I'm writing some unit tests for my Node backend using jest, and keep running into the same problem. I have a test file, let's say logic.test.js, that tests functionality from logic.js. logic.js consists of two functions - dataRequestFunction and logicFunction, where logicFunction makes use of dataRequestFunction to retrieve some data with an HTTP request and then performs some sort of data handling afterwards.
I want to mock the functionality of dataRequestFunction so that I can control what is returned, so that I know logicFunction operates on the correct data. What I've done so far is using jest.requireActual, like the following
jest.mock('./logic', () => ({
...jest.requireActual('./logic'),
dataRequestFunction: jest
.fn()
.mockImplementation(() => ({ data: 'someData' }))
}))
I then import logicFunction as usual. I want to use logicFunction in the test file, for example expect(logicFunction()).toEqual('somedata') (let's say the logic function's job is capitalizing the result from (await dataRequestFunction()).data). How do I accomplish this? With this implementation, logicFunction calls the non-mocked version of the function - however, if I call dataRequestFunction explicitly in the test file, ({ data: 'someData' }) is returned.