0

Test set state is not called when component is unmounted

I have got a custom hook which calls a promise on page load to set the data. To make sure that set state on data/error is not called when if the the component unmount I am using cancel request as below:


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
    }
}

My test are:

   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("");
    });

but I am getting error:


    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

Can someone please guide how this can be tested?

Thanks

reactdesign
  • 121
  • 9

0 Answers0