简体   繁体   English

useEffect 中的 setState 在酶中不起作用

[英]setState inside a useEffect not working in enzyme

i'm trying to test this component with state true:我正在尝试使用状态 true 测试此组件:

<DashboardBreadcrumbButtons canShare={stateHooks.state.canShare} />

But in my tests, always is false.It enters, assigns the state to true, but after it arrives in the render state is false.但是在我的测试中,始终为false。它进入,将状态分配为true,但到达渲染状态后为false。

const setStates = ({state, setState}, newState) =>
  setState(Object.assign({}, state, newState));

const [state, setState] = useState({
  isFullscreen: false,
  confirmDelete: false,
  icon: props.icon,
  iconUpload: null,
  title: props.title,
  description: props.description,
  canShare: false,
  canDefineHome: false,
  canEditPortal: false,
  canCopyPortal: false,
  canViewAudit: false,
});

useEffect(() => {
  debugger;
  // Enter here in the tests and assign
  setStates(stateHooks, {
    canShare: true,
    canDefineHome: true,
    canEditPortal: true,
    canCopyPortal: true,
    canViewAudit: true,
  });
}, []);

useEffect(() => {
  // Here, always is false in test, setStates not working
  console.log(stateHooks.state.canShare);
  debugger;
}, [stateHooks.state.canShare]);

In my application is working Application Image在我的应用程序中工作应用程序图像

setState is an asynchronous operation so its hard to predict when it will be set. setState 是一个异步操作,所以很难预测它什么时候会被设置。 you can use below code to update the wrapper component just above you assert operation.您可以使用以下代码更新断言操作上方的包装器组件。 This worked for me.这对我有用。

componentWrapper.update();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM