【发布时间】:2022-10-06 16:56:29
【问题描述】:
我正在尝试解决 React 测试中的常见警告消息
console.error
Warning: An update to EntryList 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 */
我创建了一个可以传递反应调度程序函数的钩子
export const useSafeDispatches = (...dispatches) => {
const mounted = useRef(false);
useLayoutEffect(() => {
mounted.current = true;
return () => (mounted.current = false);
}, []);
const safeDispatch = useCallback(
(dispatch) =>
(...args) =>
mounted.current ? dispatch(...args) : void 0,
// eslint-disable-next-line
[mounted.current]
);
return dispatches.map(safeDispatch);
};
而且,我正在这样使用它
function MyComponent() {
const [counter, d] = useState(0);
const [setCounter] = useSafeDispatches(d);
return <button onClick={() => setCounter(counter + 1)}>{counter}<button>
}
然而,我在测试中遇到了同样的错误(在卸载组件后我尝试调用 setState)
-
如果您的单元测试代码有问题,那么您可能应该将您的单元测试代码包含在您的minimal reproducible example 中。该错误与您测试组件/挂钩的方式有关,而不是与组件/挂钩的实现方式有关。仅供参考,使用“isMounted”检查现在也被认为是反模式。
标签: reactjs react-hooks