卸载组件时不会调用测试集状态
我有一个自定义钩子,该钩子会在页面加载时调用promise来设置数据。为了确保当我正在使用以下取消请求卸载组件时,不会调用关于数据/错误的设置状态:
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
有人可以指导如何测试吗?
谢谢