如何使用react-testing-library模拟内容溢出?

时间:2020-04-19 13:32:55

标签: javascript reactjs jestjs material-ui react-testing-library

我正在使用material-table和material ui来创建电子表格应用程序。我实现的行为之一是单元格上的最大宽度为50px。如果该单元格的内容太大,则默认在单词末尾使用省略号(请参见启用noWrap道具的Typography Material-UI组件)。如果此单元格悬停,将显示一个弹出窗口,显示该单元格的全部内容。通过检查scrollWidth> clientWidth是否检查单元格是否溢出,如果是,则启用onMouseEnter和onMouseLeave行为来显示和隐藏弹出窗口。这一切都很好。我的问题是,我正在努力在使用jest / react-testing-library编写的测试中复制这种行为。当我调用react-testing render方法时,即使单元格组件中的值很长,它也不会输出溢出行为。这是因为它是虚拟渲染,而不是在浏览器中实际渲染吗?如果是这样,是否有办法强制我执行溢出行为?我已经附加了我当前的组件,以及计算溢出功能和当前测试。

const calculateOverflow = element => {
  return element ? element.scrollWidth > element.clientWidth : false;
}
export default function OverflowCell(props) {
  const typeRef = useRef();
  const { value } = props;
  const classes = useStyles(props);
  const [anchorEl, setAnchorEl] = React.useState(null);

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

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

  const isOverflowing = calculateOverflow(typeRef.current);

  const open = Boolean(anchorEl);

  return (
    <div>
      <Typography
        ref={typeRef}
        aria-owns={open ? 'mouse-over-popover' : undefined}
        aria-haspopup={isOverflowing ? 'true' : 'false'}
        aria-label={isOverflowing ? 'overflowCell' : 'cell'}
        onMouseEnter={isOverflowing ? handlePopoverOpen : undefined}
        onMouseLeave={isOverflowing ? handlePopoverClose : undefined}
        className={classes.overFlowText}
        noWrap
      >
        {value}
      </Typography>
      {isOverflowing && (
        <Popover
          className={classes.popover}
          classes={{
            paper: classes.paper,
          }}
          open={open}
          anchorEl={anchorEl}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'left',
          }}
          transformOrigin={{
            vertical: 'top',
            horizontal: 'left',
          }}
          onClose={handlePopoverClose}
          disableRestoreFocus
        >
          <Typography>{value}</Typography>
        </Popover>
      )}
    </div>
  );
}
it('triggers popover when overflowing string is hovered', async () => {
  const cellValue = 'test value that is very longggggggggggggggggggggggggggggggggggggggggg';
  const divStyle = {
    'max-width': '10',
  };
  mockRowData[0].forname = cellValue;
  const { asFragment, getByLabelText } = render(
    <div style={divStyle}>
      <OverflowCell value={cellValue} />
    </div>,
  );
  const initialRender = asFragment();
  const overflowCell = getByLabelText('cell');
  Simulate.mouseEnter(overflowCell);
  await delay(500);
  expect(initialRender).toMatchDiffSnapshot(asFragment());
  Simulate.mouseLeave(overflowCell);
  await delay(500);
  expect(initialRender).toMatchSnapshot(asFragment());
});

1 个答案:

答案 0 :(得分:0)

我认为这是因为单元测试未在真正的浏览器中运行。因此它不会执行CSS,也不会滚动。