A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://stackoverflow.com/questions/75337197/how-can-i-test-useeffect-with-async-function-in-jest below:

reactjs - How can I test useEffect with async function in Jest?

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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4