jeudi 7 janvier 2021

Jest useFetch mocking

I'm trying to mock fetch function in my custom hook. - useFetch. And btw make some tests. But, I have some problem with fetching data. Tests return an error like so:

"Cannot read property 'json' of undefined at getData".

Here's useFetch.js:

import { useEffect, useState } from 'react';

export default function useFetch(apiUrl) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const getData = async (url) => {
      setLoading(true);
      try {
        const response = await fetch(url);
        const data = await response.json();
        setData(data);

        return data;
      } catch(e) {
        setError(e);

        return e;
      } finally {
        setLoading(false);
        return;
      }
    }

    getData(apiUrl);
  }, [apiUrl]);


  return {data, loading, error};
};

And here is my useFetch.test.js

import { renderHook } from '@testing-library/react-hooks'
import useFetch from './useFetch';
const DATA_MOCK = {
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
};
describe('useFetch', () => {
  beforeAll(() => {
    global.fetch = jest.fn(() =>
      Promise.resolve({
        json: () => Promise.resolve({
          "userId": 1,
          "id": 1,
          "title": "delectus aut autem",
          "completed": false
        }),
      })
    );
  });
  afterAll(() => {    
    global.fetch.mockClear();
  });
  test('should return data', async () => {
    const { result, waitForNextUpdate } = renderHook(() => useFetch('https://jsonplaceholder.typicode.com/todos/1'));
    await waitForNextUpdate();
    console.log(result.current);
    // console.log
    // {
    //   data: null,
    //   loading: false,
    //   error: TypeError: Cannot read property 'json' of undefined
    //       at getData (/Users/kkowalczuk/Documents/Moje/RTL/random-components-practice/src/hooks/useFetch/useFetch.js:13:37)
    // }
    expect(result.current.data).toBeTruthy();  // problem
    expect(result.current.data).toMatchObject(DATA_MOCK);
    expect(result.current.loading).toBeFalsy();
    expect(result.current.error).toBeNull();
});
});

So, as You see the problem is .json(). But i completely don't know where exactly, with my mock? With my code? I will be grateful for any suggestions.

Aucun commentaire:

Enregistrer un commentaire