Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing nested menu items in react material-ui menu

I want to test my menu which has nested menu items. I want to be able to simulate a click on a nested menu item and see if it's handler is called. I already got the tests for not nested menu items working.

Here is a simple version of the test I am trying to build:

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?
  }) 
})

I'm using this simulateEvent to simulate the touch tap:

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

I am using React 15.6.1, material-ui 0.18.6, Enzyme 2.9.1 Jest 20.0.4

Maybe related? React, Jest and Material-UI: How to test for content rendered in a modal or popover

like image 594
Robbert van Markus Avatar asked Aug 31 '17 11:08

Robbert van Markus


Video Answer


1 Answers

After some learning about Enzyme I found out that they are using jsdom to have a headless browser implemented with the actual DOM. What I did to fix my problem was replacing the component.find("#nested") method with a document.findElementById('#nested'). After that, the test could find the child components and passes.

like image 109
Robbert van Markus Avatar answered Sep 22 '22 00:09

Robbert van Markus