score:0

You could try to mock the fetch library.

In the test setup:

global.fetch = jest.fn()

And then in your test:

global.fetch.mockResolvedValue({ json: () => ({ data: "" })})

score:2

I Will suggest to put your hook in separate file lets say useFetch.js conntains

import { useEffect, useState } from "react";

export const useFetch = (url: string) => {
  const [data, setData] = useState();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fetch(url);
        const json = await res.json();
        setData(json);
      } catch (error) {
        console.log(error);
      }
    };

    fetchData();
  }, [url]);

  return data;
};

Keeping your app component file like follows

import React from "react";

import { useFetch } from "./useFetch";


const App = () => {
  const config = useFetch(`/api/url`);

  return (
    <div></div>
  );
};

export default App;

with above split you can easily mock your hook, example test file as follows

import React from "react";
import { render } from "@testing-library/react";
import App from "./App";


// mock config
const mockConfig = {
    data: "mock data"
};

// this will mock complete file, we have provided mock implementation
// for useFetch function
jest.mock("./useFetch", () => ({
    useFetch: () => mockConfig
}));

test("should render with mock useFetch", () => {
    const { getByText } = render(<App />);
    // test logic goes here
});


Assuming all the files are in same directory.


Related Query

More Query from same tag