2

I am trying to test useEffect and function calls inside useEffect in below code. It has useEffect and useState hooks.

const App = () => {
  const [search, setSearch] = useState("");
  const [images, setImages] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const getImageData = async () => {
    console.log(getImages());
    const { data, error } = await getImages();
    handleData(data, error);
  };

  const searchImageData = async (search) => {
    const { data, error } = await searchImages(search);
    handleData(data, error);
  };

  const handleData = (data, error) => {
    setLoading(true);
    if (data) {
      setImages(data);
    } else if (error) {
      setError(error);
    }
    setLoading(false);
  };

  // get images using hooks
  useEffect(async () => {
    if (search.length > 0) {
      searchImageData(search);
    } else {
      getImageData();
    }
  }, [search]);

  return (
    <center>
      <h1>Photo Search App</h1>
      <SearchBox search={search} setSearch={setSearch} />
      <div className="photo-container">
        {loading ? (
          <p>Loading</p>
        ) : error ? (
          <p>Error loading data</p>
        ) : images.length > 0 ? (
          <Gallery images={images} />
        ) : (
          <p>No photos found</p>
        )}
      </div>
    </center>
  );
};

I am not sure how to mock the things related to hooks. Any suggestion of testing the hook and async function calls?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
TnJ
  • 43
  • 4
  • If you mount your component, you don't have to mock React hooks then. You can try this package `https://testing-library.com/docs/react-testing-library` which is pretty common for now – tmhao2005 Dec 25 '20 at 11:45
  • Testing React functional component using hooks useEffect, useDispatch and useSelector in shallow renderer with Jest + Enzyme https://medium.com/@pylnata/testing-react-functional-component-using-hooks-useeffect-usedispatch-and-useselector-in-shallow-9cfbc74f62fb – Daniil Loban Dec 25 '20 at 11:47
  • @tmhao2005 how to test getImageData() ? – TnJ Dec 25 '20 at 11:56
  • You absolutely have to mock your service data with jest – tmhao2005 Dec 25 '20 at 12:13
  • *Don't* mock the hooks, you don't own React's API. Mock the *collaborators*, `searchImages` and `getImages`. – jonrsharpe Dec 25 '20 at 12:57

0 Answers0