BlackWhite
BlackWhite

Reputation: 832

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

Upvotes: 0

Views: 285

Answers (0)

Related Questions