mocking my fetch function does not work, keeps getting back undefined

Viewed 115

I am trying to mock a simple function that uses fetch. The function in question looks like this:

export const getPokemon = async () => {
  //function that makes the API call and fetches our pokemon
//getPokemon.js
  const randomId = () => Math.floor(Math.random() * 151 + 1);

const pokemonApiUrl = `https://pokeapi.co/api/v2/pokemon/`;

export const getPokemon = async () => {
  //function that makes the API call and fetches our pokemon
  const id = randomId();
  let pokemon = { name: "", image: "" };
  try {
    const result = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`);
    console.log(result)
    const data = await result.json();
    pokemon.name = data.name;
    pokemon.image = data.sprites.other["official-artwork"].front_default;
    return pokemon;
  } catch (err) {
    console.error(err);

Whenever I try to mock the function in my unit tests I receive back a TypeError: Cannot read property 'json' of undefined. Basically, the result comes back as undefined and thus we cannot call our .json(). It works fine in production and the fetch calls work as expected. I am using React Testing Library and Jest.

I have tried to replaced the global fetch in the following manner:

//PokemonPage.test.js
global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve({ data: { name: 'Charizard' } }),
  })
);

I've also tried to create a fakeFetch and send it in to my function as a dependency injection, but I get the exact same error.

Lastly, I've tried to install jest-fetch-mock but yet again I am getting the same error... Has anyone encountered the same thing?

The failing function gets called in production here:

function Pokemon({ pokemonTrainer }) {
...
  useEffect(() => {
    async function fetchData() {
      pokemonRef.current = await getPokemon();
      setPokemonList((prev) => [
        ...prev,
        { name: pokemonRef.current.name, image: pokemonRef.current.image },
      ]);
    }
    fetchData();
  }, []);
...
}
0 Answers
Related