mercredi 2 décembre 2020

Test hooks in react components

I'm looking for a way to test the react hooks have done what they need to do in my component. I know that you can't test the hooks directly, so I want to test the side effects but cannot see how. Any help with how to test the axios call would be appreciated too.

I'm using react-testing-library and TypeScript.

This is how my component is structured:

const MyComponent: React.FC = () => {
  const [myData, setMyData] = React.useState({ data: [] });
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(false);

  const fetchData = async () => {
    await axios({
      method: 'GET',
      url: `${config.Api}/data`,
    }).then(result => {
      setLoading(false);
      setMyData(result);
    }).catch(() => {
      setError(true);
    });
  };

  React.useEffect(() => {
    fetchData();
  }, []);

  return (...);
};

Aucun commentaire:

Enregistrer un commentaire