Mocking global fetch, but the fetch returns undefined only in the test

Viewed 19

I'm not sure what's going on but I been following a bunch of tutorials and I don't think I'm doing anything wrong. Once I try to override the global fetch, it errors saying "result" variable is undefined.

How can I fix this?

my RTL test

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve({ test: "hello world" }),
  }),
) as jest.Mock;

it('should render AAA Component', async () => {
  render(<AAA />);
}

my component

const AAA = () => {
  const [data, setData] = useState(null);

  const getData = async () => {
    let result;
    try {
      result = await fetch("https://pokeapi.co/api/v2/pokemon?limit=151");
      const data = await result.json(); <-- ERRORS HERE; says "result" is undefined
      setData(data);
    } catch (error) {
      console.log(error);
    }
  }

  useEffect(() => {
    getData();
  }, []);
0 Answers
Related