如何使用Jest和Enzyme在我的React组件中测试此功能

时间:2019-11-13 18:03:44

标签: reactjs jestjs material-ui enzyme

在我的react应用程序中,我缺少组件上一个功能的测试范围。我在弄清楚如何进行测试以及提高测试范围时遇到了麻烦。

我的组件

    export const InfoIconWrapper = styled(InfoIcon)(({ theme }) => ({
      color: fade(theme.palette.black, 0.3),
    }));

    export const GridWrapper = styled(Grid)(({ theme }) => ({
      pointerEvents: 'none',
      padding: theme.spacing(1),
    }));

const DistributionLinePopover = ({ distributionLine }) => {
  const [anchorEl, setAnchorEl] = useState(null);

  const handlePopoverOpen = event => {
    setAnchorEl(event.currentTarget);
  };

  const handlePopoverClose = () => {
    setAnchorEl(null);
  };

  const open = Boolean(anchorEl);
  const mouseOverPopover = 'mouse-over-popover';
  return (
    <Fragment>
      <Typography
        aria-owns={open ? mouseOverPopover : undefined}
        aria-haspopup="true"
        onMouseEnter={handlePopoverOpen}
      >
        <InfoIconWrapper fontSize="small" />
      </Typography>
      <Popover
        id={mouseOverPopover}
        open={open}
        anchorEl={anchorEl}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'left',
        }}
        onMouseOut={handlePopoverClose}
        disableRestoreFocus
      >

我要测试的是handlePopoverClose函数。我当前的测试:

    it('it should exercise hover state', () => {
  const component = mount(
    <MuiThemeProvider theme={theme}>
      <DistributionLinePopover distributionLine={distributionLine} />
    </MuiThemeProvider>
  );

  expect(component.find(Popover).props().anchorEl).toBe(null);

  component
    .find(Typography)
    .first()
    .simulate('mouseenter');

  expect(component.find(Popover).props().anchorEl).toBeTruthy();

  component
    .find(Typography)
    .first()
    .simulate('mouseleave');

  expect(component.props().anchorEl).toBeFalsy();
});

当用户将鼠标悬停在Popover元素上时,应将anchorEl设置为null。如果那太困难了,那么我可以解决一下该函数是否被调用的问题。我时间不多了,目前的目标是仅仅提高测试覆盖率

0 个答案:

没有答案