testing-library / react-testing-library

🐐 Simple and complete React DOM testing utilities that encourage good testing practices.

Home Page:https://testing-library.com/react

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`result.current` shows `undefined` in console logger while rendering a custom hook

meeowngit opened this issue · comments

  • @testing-library/react version: 13.4.0
  • Testing Framework and version: Vitest v1.0.4
  • DOM Environment: jsdom v23.0.1

Relevant code or config:

  • test code
import { act, renderHook, waitFor } from "@testing-library/react";

describe("useFetch", () => {
    const url = "https://jsonplaceholder.typicode.com/posts";

    test(" fetched data", async () => {
        //render custom hook is not working 
        const { result } = renderHook(() => {
            useFetch(url, []);
        });
        console.log(result.current); //undefined 
    });
});

This is the custom hook

useEffect(() => {
		(async () => {
			try {
				const res = await axios.get(url);
				console.log(res.data)  // It works fine
				setNews(res.data.articles);
			} catch (err) {
				console.log(err)
				setError(err.message);
			} finally {
				console.log("or maybe still loading...")
				setLoading(false);
			}
		})();
	}, [url]);

	return {
		loading,
		news,
		error,
	};

What you did:

I tried to test the custom hook it gives me undefined:

 RERUN  src/test/useFetch.test.js x64

stdout | src/test/useFetch.test.js > useFetch > fetched data
undefined
{ userId: 1, id: 1, title: 'mocked title', body: 'mocked body' }
or maybe still loading...

What happened:

Reproduction:

Problem description:

Suggested solution:

Hi @meeowngit, this issue is missing some information for us to understand like - is the network call mocked?
As an idea, I believe you're just missing a waitFor. The fetch call isn't synchronous so your test moves to the next line before the fetch call is resolved.
I'm closing this as this doesn't seem like an issue with the library. If you feel like this is incorrect, please re-open or comment here.

@MatanBobi Thank you for your response!

actually I sorted it out the solution what I was doing wrong is that: I inserted this extra curly braces to useFetch hook.

 const { result } = renderHook(() => useFetch(url, []));

you will see in the above code there is no extra curly braces, due to that result.current doesn't show anything and returns undefined.