0

I have this function inside a helper:

export const useDAMProductImages = (imageId: string) => {
  const {
    app: { baseImgDomain },
  } = getConfig();
  const response: MutableRefObject<string[]> = useRef([]);

  useEffect(() => {
    const getProductImages = async (imageId: string) => {
      try {
        const url = new URL(FETCH_URL);

        const res = await fetchJsonp(url.href, {
          jsonpCallbackFunction: 'callback',
        });
        const jsonData = await res.json();

        response.current = jsonData;
      } catch (error) {
        response.current = ['error'];
      }
    };

    if (imageId) {
      getProductImages(imageId);
    }
  }, [imageId]);

  return response.current;
};

In test file: import .....

jest.mock('fetch-jsonp', () =>
  jest.fn().mockImplementation(() =>
    Promise.resolve({
      status: 200,
      json: () => Promise.resolve({ set: { a: 'b' } }),
    }),
  ),
);

describe('useDAMProductImages', () => {
  beforeEach(() => {
    jest.clearAllMocks();
    cleanup();
  });

  it('should return empty array', async () => {
    const { result: hook } = renderHook(() => useDAMProductImages('a'), {});
    expect(hook.current).toMatchObject({ set: { a: 'b' } });
  });
});

The problem is that hook.current is an empty array. Seems that useEffect is never called. Can someone explain to me what I'm doing wrong and how I should write the test? Thank you in advance

2
  • Can you explain the bigger picture? This test code does not test anything other than your mock'd function and JavaScript/React internals. Even if useEffect performed the way you expect, you've only tested JavaScript/React internals. So what is the value in this test beyond what you have shared here? Commented Feb 3, 2023 at 15:01
  • I want to check if I call useDAMProductImages with imageId as a empty string, the function should return empty array and if the imageId is not empty the function should return a json data ({ set: { a: 'b' } }) Commented Feb 3, 2023 at 15:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.