Custom Hook: как проверить состояние набора не вызывается при размонтировании компонента - PullRequest
0 голосов
/ 20 сентября 2019

Состояние тестового набора не вызывается, когда компонент отключен

У меня есть пользовательская ловушка, которая вызывает обещание при загрузке страницы для установки данных.Чтобы убедиться, что установленное состояние данных / ошибки не вызывается, когда компонент размонтируется, я использую запрос отмены, как показано ниже:


function useService() {
    const [data, setData] = useState([]);
    const [error, setError] = useState("");
    const [loading, setLoading] = useState({});
    const [cancelRequest, setCancelRequest] = useState(false);

    const getMessgaes = async () => {
        setLoading(true);
        try {
            const res = await getChatLog();
            if (!cancelRequest) {
                setData(res);
                setLoading(false);
            }
        } catch (e) {
            if (!cancelRequest) {
                setError(e);
                setLoading(false);
            }
        }

    };

    useEffect(() => {
        getMessgaes();
        return () => {
            setCancelRequest(true);
        };
    }, []);


    return {
        data, error, loading, cancelRequest
    }
}

Мой тест:

   it("if component is unmounted before response then set data is not called", async () => {
        getChatLog.mockImplementation(() => {
            setTimeout(()=>{
                Promise.reject("error");
            },500);
        });
        const {result, unmount, waitForNextUpdate} = renderHook(() => useService());
        expect(result.current.cancelRequest).toEqual(false);
        unmount();
        expect(result.current.cancelRequest).toEqual(true);
        await waitForNextUpdate();
        expect(getChatLog).toHaveBeenCalledTimes(3);
        expect(result.current.error).toEqual("");
    });

, ноЯ получаю сообщение об ошибке:


    Warning: An update to TestHook inside a test was not wrapped in act(...).

    When testing, code that causes React state updates should be wrapped into act(...):

    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */


    Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
        in TestHook
        in Suspense

Может кто-нибудь подсказать, как это можно проверить?

Спасибо

...