[英]Initializing state, while testing a component with useState using jest & enzyme
This question is not for testing state change, but for setting initial value to true.这个问题不是为了测试状态变化,而是为了将初始值设置为 true。 So that menu will be opened and I can test onClick functionally on the opened menu.
这样菜单将被打开,我可以在打开的菜单上测试 onClick 的功能。 I am using Jest and Enzyme.
我正在使用 Jest 和 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'>
{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
.如您所见,如果 anchorEl 为 true 菜单将被打开,我可以通过单击Profile
Menubutton
来测试onProfileClicked()
是否被调用。 My question is, in my test how can I set anchorEl
to true?我的问题是,在我的测试中,如何将
anchorEl
设置为 true? As wrapper.setState()
can only be done for class components and not for functional with hooks.因为
wrapper.setState()
只能用于类组件,不能用于带有钩子的函数。
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.如果您使用的是
shallow()
您也可以传递{target: null}
,但对于mount()
它取决于<Menu>
实现,如果只是一个document
可以工作,或者您需要传递一些嵌套的DOM 元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.