jeudi 10 décembre 2020

How can I test my custom react hook that uses fetch?

I have created a custom react hook which uses fetch from whatwg-fetch. I have tests for the components that make use of the hook and can mock the whole hook, but now am trying to write tests for the hook itself and my goal is to mock the fetch response. This is my hook.

import "whatwg-fetch";

function useFetch(url) {
    const [data, setData] = useState(undefined);
    const [response, setResponse] = useState(undefined);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState(undefined);

    useEffect(() => {
        try {
            const fetchData = async () => {
                setIsLoading(true);

                const result = await fetch(url);
                setResponse(result);

                const responseText = await result.text();
                setData(responseText);

                setIsLoading(false);
            };
            fetchData();
        } catch (e) {
            setError(e);
        }
    }, [url]);

    return {
        data, response, isLoading, error
    };
}

export { useFetch };
export default useFetch;

Currently, this is how my test looks like. Feels like I cannot mock the fetch to return the desired value.

I have tried writing tests by looking at several tutorials with no luck. I have tried the following tutorials:

import { useFetch } from "../../../src/utils/custom-hooks/useFetch";

describe("useFetch tests", () => {
    beforeEach(() => {
        jest.spyOn(window, "fetch");
    });

    it("200", () => {
        window.fetch.mockResolvedValueOnce({
            ok: true,
            status: 200,
        })
        const { result, rerender } = renderHook(
            (url) => useFetch(url),
            {
                url: "url1"
            }
        );
        expect(result.current.response).toBe(undefined);
        rerender("url2");
        expect(result.current.status).toBe(200);
    });
});

Aucun commentaire:

Enregistrer un commentaire