测试React自定义钩子

时间:2019-07-27 05:03:03

标签: javascript reactjs jestjs react-hooks jest-fetch-mock

我正在尝试为我的功能组件创建一个自定义挂钩,但是我无法对其进行单元测试。

function useFetch(url: string) {
    const [options, setOptions] = useState();
    const [loading, setLoading] = useState(false);

    async function fetchStuff() {
        setLoading(true);
        try {
            const response = await fetch(url); // Note that this is a custom fetch method
            if (response.ok) {
                const options = await response.json();
                setOptions(json);
            } else {
                console.log("Error has occured while retrieving variants: ", response);
            }
        } catch (error) {
            console.log("Error has occured while retrieving variants or parsing options: ", error);
        }
        setLoading(false);
    }

    useEffect(() => {
        fetchStuff();
    }, []);

    return [loading, options];
}

export default useFetch;

测试:

describe("useFetch", () => {
    it("should return product options if it were retrieved and parsed successfully", async () => {
        const mockResponse = {
            status: 200,
            text: () => "true",
        };
        const mockFetch = { default: jest.fn(() => Promise.resolve(mockResponse)) };
        jest.mock("../../../../utils/fetch", () => mockFetch);

        const { result, waitForNextUpdate } = renderHook(() =>  useFetch("someUrl"));

        await waitForNextUpdate();

        expect(result.current[0]).toEqual(false); // Times out
    });
});

运行测试时,它只是超时。我是否采取正确的方法?我最好只是在将挂钩包裹在组件中时对其进行测试吗?我认为功能组件+挂钩的好处之一是,它允许可重复使用的挂钩,可以轻松地对其进行单元测试。

当我调试测试时,它似乎没有超出第一个useState调用。我是React开发的新手,所以任何评论都将不胜感激。

0 个答案:

没有答案