Max Lynn
Max Lynn

Reputation: 441

How do you mock a function inside another function with Jest

I'm trying to figure out how to write a jest test for this code that is written outside of a class in a react component.

export const getContent = async (id) => {
   const idCheck = id ? id : '';

   return (
     apiCall('get', 'api/content', null, { id: idCheck }).then((response) => {
       const addingKey = addKey(response.data.getContent);
       return addingKey;
   }))
};

This is written outside of a class and I have imported the method to my tests like so:

import { getContent } from '../../../client/pages/content';

If I run these tests I get that response.data.getContent is not defined which makes sense because I haven't mocked or spyed on apiCall.

 const content = await getContent();
 expect(content).toEqual(response);

So what I'm trying to do is mock the response that apiCall is giving me so I can send it different data to test if addKey is working how I expect.

I've tried to mock the apiCall and tried to spy on it but I don't think I'm understanding how to do it correctly:

const spy = jest.spyOn(getContent, 'apiCall');
apiDependency.apiCall = jest.fn(() => response)

Upvotes: 1

Views: 532

Answers (1)

Satyam Jain
Satyam Jain

Reputation: 11

Can you try something like this?

jest.mock("someModule/someFile", () => {
    const originalModule = (jest as any).requireActual("someModule/someFile");
    return {
        ...originalModule,
        someOtherFuncs: {
            ...originalModule.someOtherFuncs,
            apiCall: jest.fn(() => {
                return response;
            }),
        },
    };
});

Upvotes: 1

Related Questions