Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
How to Test useEffect Fetch with Jest in React

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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!