4

How do I test my useEffect Fetch with Jest in React? I've tried looking for answers and found a code that I copied to try out but am still failing the test. I haven't used Jest before and am currently trying to implement it in a code I'm working on.

Here is my test inside my test.js file:

  it('Displays days from 1 to 31', async () => {
    expect(useEffectTest).toBe([{ day: 1 }]);
  });

And here is the useEffect in another component called calendar.jsx:

 const useEffectTest = () => {
  const [daysData, setDaysData] = useState([]);

  useEffect(() => {
    fetch('http://localhost:5001/chocolates')
      .then((resp) => resp.json())
      .then((data) => setDaysData(data));
  }, []);

  console.log(daysData);
};

I want to test if the fetched api is acquiring this data from an array of objects:

{ day: 1, status: 'empty' || 'open' }

Thanks for any help in advance.

1 Answer 1

2

Firstly, you need to update your unit test to call your function, like this:

it('Displays days from 1 to 31', async () => {
    expect(useEffectTest()).toBe([{ day: 1 }]);
});

That's because expect needs to have the data returned from your useEffectTest function passed in to it.

However, this will still fail because your function isn't returning anything. So we need to update useEffectTest to return daysData, like this:

 const useEffectTest = () => {
  const [daysData, setDaysData] = useState([]);

  useEffect(() => {
    fetch('http://localhost:5001/chocolates')
      .then((resp) => resp.json())
      .then((data) => setDaysData(data));
  }, []);

  return daysData;
};

Next up, we usually don't want to make network requests from unit tests. That's because network requests can make unit tests slow, and brittle. For example, if your API server goes down, we would still want the unit tests to pass. To get around these problems we need to mock the fetch request. A popular way to mock fetch requests is with the jest-fetch-mock library.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your answer and for the help :) Sure glad to learn something new

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.