reactjs – React,Jest和Material-UI:如何测试在模态或弹出窗口中呈现的内容

有一些material-ui组件不会将其结果呈现在与其父组件放置组件相同的位置.其中我们有Dialog,Menu等.

这使得显然无法在jest.js包装器中测试其内容是否存在,其中包含一些父组件.

例如,给出以下组件:

class DropdownMenu extends React.Component {
  onButtonClick = (e) => {
    this.setState({ open: true,anchorEl: e.currentTarget });
  }

  render() {
    return (
      <div>
        <Button onClick={this.onButtonClick}>Menu</Button>
        <Menu
          open={this.state.open}
          onRequestClose={() => this.setState({ open: false })}
        >
          <MenuItem label="Home" />
          <MenuItem label="Sign in" />
        </Menu>
      </div>
    );
  }
}

即使它应该直观地工作,此测试也会失败:

it('renders some menu items',() => {
  const wrapper = mount(<AppMenu />);
  expect(wrapper).toContainReact(<MenuItem label="Home" />);
});

这是Jest失败的输出:

renders some menu items

Expected <AppMenu> to contain <withStyles(MenuItem) className="MenuItem" component={{...}} to={{...}}>Home</withStyles(MenuItem)> but it was not found.
HTML Output of <AppMenu>:
 <div><button tabindex="0" class="MuiButtonBase-root-3477017037 MuiButton-root-3294871568 MuiButton-flatContrast-53993421" type="button" role="button" aria-owns="simple-menu" aria-haspopup="true"><span class="MuiButton-label-49836587">Menu</span><span class="MuiTouchRipple-root-3868442396"></span></button><!-- react-empty: 5 --></div>

正如您所看到的,就像所有呈现的一样是< Button>.实际上,当您在浏览器中渲染上述组件并展开菜单并检查它的菜单项元素时,它们将呈现在DOM中的其他位置,而不是在按钮出现的位置内或甚至附近.它们实际上是在div< body>< div data-mui-portal =“true”>内呈现的. …< / div>直接在文件的< body>下元件.

那么如何测试这个菜单内容呢?

解决方法

在状态更改之前,菜单不会呈现,因此您可以模拟Button上的单击,让其处理程序设置为StateState,触发重新呈现,并查找特定的MenuItem.

此外,这可能无需完全安装即可完成:

it('renders some menu items',() => {
  const wrapper = shallow(<AppMenu />);

  // find the Menu Button
  const button = wrapper.findWhere(node => node.is(Button) && n.prop('children') === 'Menu');

  // simulate a click event so that state is changed
  button.simulate('click');

  // find the Home MenuItem
  const menuItem = wrapper.findWhere(node => node.is(MenuItem) && n.prop('label') === 'Home');

  // make sure it was rendered
  expect(menuItem.exists()).toBe(true);
});

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...