1
votes

This question is not for testing state change, but for setting initial value to true. So that menu will be opened and I can test onClick functionally on the opened menu. I am using Jest and Enzyme.

Component:



const CustomHeader = () => {


  const [anchorEl, setAnchorEl] = useState(null)



  const open = Boolean(anchorEl)

  const handleMenu = event => {
    setAnchorEl(event.currentTarget)
  }

  const handleClose = () => {
    setAnchorEl(null)
  }

  const onProfileClicked = () => {
    dispatch(setProfileShown(true))
    dispatch(setEditMode(false))
    handleClose()
  }

  return (
    <Header position='fixed'>
      <HeaderContent>

        <>
          <ProfileButton
            aria-label='account of current user'
            aria-haspopup='true'
            onClick={handleMenu}
            color='primary'
          >
            <ProfileIcon color='primary' />
            <HeaderTitle variant='subtitle1'>
              &nbsp;{user.firstName}
            </HeaderTitle>
          </ProfileButton>
          <Menu
            id='menu-appbar'
            anchorEl={anchorEl}
            open={open}
            onClose={handleClose}
          >
            <MenuItem onClick={() => onProfileClicked()}>Profile</MenuItem>
            <MenuItem onClick={() => dispatch(signOut())}>Logout</MenuItem>
          </Menu>
        </>
      </HeaderContent>
    </Header>
  )
}


As you can see, if anchorEl is true Menu will be opened and i can test onProfileClicked() is called or not by clicking Profile Menubutton. My question is, in my test how can I set anchorEl to true? As wrapper.setState() can only be done for class components and not for functional with hooks.

1

1 Answers

0
votes

just trigger appropriate interaction:

wrapper.find({ 'aria-label': 'account of current user' }).simulate({ target: document });

If you are using shallow() you may pass {target: null} as well but for mount() it depends on <Menu> implementation if just a document would work or if you need to pass some nested DOM element.