简体   繁体   中英

setState inside a useEffect not working in enzyme

i'm trying to test this component with state 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.

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. you can use below code to update the wrapper component just above you assert operation. This worked for me.

componentWrapper.update();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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