加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – React,Jest和Material-UI:如何测试在模态或弹出窗口

发布时间:2020-12-15 09:30:49 所属栏目:百科 来源:网络整理
导读:有一些material-ui组件不会将其结果呈现在与其父组件放置组件相同的位置.其中我们有Dialog,Menu等. 这使得显然无法在jest.js包装器中测试其内容是否存在,其中包含一些父组件. 例如,给出以下组件: class DropdownMenu extends React.Component { onButtonCli
有一些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);
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读