[我有一个简单的材质用户界面ListItem
的示例,我将其鼠标悬停在其中,而包含另一个Popper
的材质用户界面ListItem
随后出现在onMouseOver
事件上。这可以正常工作,但是我无法在相关的笑话/酶测中复制该行为。
在此处删除失败的示例。
Component Snippet
export default function MyPopoutMenu() {
const [popoverAnchorElement, setPopoverAnchorElement] = useState(null);
const handleMouseEnter = event => {
console.log("onMouseEnter - " + event.currentTarget.textContent);
setPopoverAnchorElement(event.currentTarget);
};
const handleClose = (event, index) => {
console.log("closing");
setPopoverAnchorElement(null);
};
let isPopoverOpen = Boolean(popoverAnchorElement);
return (
<div className="App">
<List style={{ maxWidth: "250px" }}>
<ListItem button>
<ListItemIcon>
<FolderIcon />
</ListItemIcon>
<ListItemText onMouseEnter={handleMouseEnter}>
Hover on me
</ListItemText>
</ListItem>
</List>
<Popper
open={isPopoverOpen}
onClose={handleClose}
anchorEl={popoverAnchorElement}
className="popper-item"
>
<ListItem button>
<ListItemIcon>
<KeyboardArrowRightIcon />
</ListItemIcon>
<ListItemText>I Appear</ListItemText>
</ListItem>
</Popper>
</div>
);
}
测试代码段
const wrapper = mount(<MyPopoutMenu />);
//1. Find the menu item to hover on
const foundListItem = wrapper
.find(".MuiListItemText-root")
.filterWhere(item => item.contains("Hover on me"));
expect(foundListItem).toHaveLength(1);
//2. Hover on the item
foundListItem.simulate("mouseover");
//Now try to find the Popover
const foundPopoverListItem = wrapper
.find(".MuiListItemText-root")
.filterWhere(item => item.contains("I Appear"));
//THIS FAILS WHEN IT DOESN'T FIND THE POPOVER WHICH SHOULD HAVE APPEARED
expect(foundPopoverListItem).toHaveLength(1);
您应该看一下有关simulate
使用的讨论:
https://github.com/airbnb/enzyme/issues/1606
因此,简而言之,建议使用not完全使用它,但改为执行以下操作:
foundListItem.prop('onMouseEnter')();
您甚至可以如下将模拟事件传递给handleMouseEnter
函数:
foundListItem.prop('onMouseEnter')({
currentTarget: {
textContent: 'I Appear'
}
});
希望这会有所帮助!