reactjs - 在 react material-ui 菜单中测试嵌套菜单项

标签 reactjs testing material-ui jestjs enzyme

我想测试具有嵌套菜单项的菜单。我希望能够模拟对嵌套菜单项的单击,并查看是否调用了它的处理程序。我已经对非嵌套菜单项进行了测试。

这是我尝试构建的测试的简单版本:

describe("menu", () => {
 it("should click on nested nested menu items", () => {
    const testOnClickSpy = Sinon.spy(() => {});
    const component = mount(
      <MuiThemeProvider><Menu>
        <MenuItem 
          primaryText={<span id="test">test</span>} onTouchTap={testOnClickSpy}
          menuItems={ <MenuItem  primaryText={<span id="nested">nested</span>} /> }/>
        </Menu></MuiThemeProvider>
    );

    simulateEvent(component.find("#test"), "touchTap");

    expect(component.find("#test").exists()).toBe(true);  // Works fine.
    expect(testOnClickSpy.callCount).toBe(1); // Works fine.
    component.update(); // <--- Does not seem to do anything?
    expect(component.find("#nested").exists()).toBe(true); // <--- Because this item cannot be found?
  }) 
})

我正在使用此 simulateEvent 来模拟触摸点击:

require("react-tap-event-plugin")();
function simulateEvent(wrappedTarget, eventType) {
    const domNode = findDOMNode(wrappedTarget["node"]);
    Simulate[eventType](domNode);
}

我正在使用 React 15.6.1、material-ui 0.18.6、Enzyme 2.9.1 Jest 20.0.4

可能相关? React, Jest and Material-UI: How to test for content rendered in a modal or popover

最佳答案

在了解了 Enzyme 之后,我发现他们使用的是 jsdom使用实际的 DOM 实现 headless 浏览器。我为解决问题所做的工作是用 document.findElementById('#nested') 替换 component.find("#nested") 方法。之后,测试可以找到子组件并通过。

关于reactjs - 在 react material-ui 菜单中测试嵌套菜单项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45980676/

相关文章:

javascript - 单击链接时,我试图关闭 React Bootstrap 中的 offcanvas 菜单

javascript - 如何使用 React 在前端 UI 上显示 API 响应消息?

perl - 如何在 Perl 中自动执行一系列测试?

reactjs - Material UI select throws event.target.getAttribute 在react-datatable-component 中使用时不是一个函数

javascript - 将 Prop 传递给 makeStyles 并在 Material UI 的 CSS 速记属性中使用

javascript - Material ui onClose 作为 disableBackdropClick 的替代品

javascript - 从 Electron 的全局快捷方式调用 React 组件中的方法

javascript - 在浏览器中调用 oAuth2 api 时出现 404 错误

ruby-on-rails - 如何将 Grunt 与 Rails Asset Pipeline 集成

javascript - AngularJS:在 $httpBackend.flush() 之前需要 $digest