React test - how to test functions inside jsx rendered with render props

1.2k Views Asked by At

I would like to test the content of the jsx that gets rendered with render prop. I use react-test-renderer for testing.

This is the Menu component that has a render prop which I would like to test:

   <Menu
      menuItems={createMenuItems(cities, onOpenCity)}
      render={(openMenu, onClick, children) => (
        <>
          <Button
            buttonRef={node => this.anchorEl = node}
            onClick={onClick}
            className={`${classes.iconWrapper} ${classes.marginIcons} ${openMenu && classes.active}`}
            <Book fill={openMenu ? '#000' : '#fff'}/>
          </Button>
          {children(this.anchorEl)}
        </>
      )}
    >
    </Menu>

The Menu component looks like this:

class Menu extends React.Component {
  static propTypes = {
    menuItems: PropTypes.arrayOf(PropTypes.shape({text: PropTypes.string, defaultAction: PropTypes.object})).isRequired
  };

  state = {
    openMenu: false,
  };

  onToggleMenu() {
    this.setState(prevState => ({openMenu: !prevState.openMenu}))
  }

  onCloseMenu() {
    this.setState({openMenu: false})
  }

  render() {
    const {openMenu} = this.state;
    const {classes, render, menuItems} = this.props;

    return render(
      openMenu,
      () => this.onToggleMenu(),
      (anchorEl) => (<Popper open={openMenu} anchorEl={anchorEl} placement="bottom-end" transition
                             disablePortal>
          {({TransitionProps, placement}) => (
            <Grow
              {...TransitionProps}
              id="menu-list-grow"
              style={{transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom'}}
            >
              <Paper>
                <ClickAwayListener onClickAway={() => this.onCloseMenu()}>
                  <MenuList disablePadding>
                    {menuItems.map(menuItem => (
                      <MenuItem
                        key={menuItem.text}
                        className={classes.menuItem}
                        onClick={() => {
                          menuItem.action();
                          this.onCloseMenu();
                        }}>{menuItem.text}</MenuItem>
                    ))}
                  </MenuList>
                </ClickAwayListener>
              </Paper>
            </Grow>
          )}
        </Popper>
      ))
  }
}

I am trying to write some tests for this component:

describe('Menu', () => {
  const context = setupTeardownWithTestRenderer();
  const menuItems = [
    {
      text: '1st item',
      action: () => {}
    }
  ];
  const renderFunction = (openMenu, onClick, children) => children(<Button onClick={onClick}>Menu</Button>);

  function renderMenu() {
    const WithRootMenu = withRoot(Menu);
    const testRenderer = context.render(<WithRootMenu menuItems={menuItems} render={renderFunction}/>);
    return testRenderer.root.findByType(Menu.Naked);
  }

  it('renders menu', () => {
    const menu = renderMenu();
    expect(menu.instance.state.openMenu).toBeFalsy();
    const menuList = menu.findByType(MenuList);
    console.log(menuList);
  });
});

I am trying to get the MenuList since I would like to test the functions on onClick prop of MenuItem component. I am setting up test with setupTeardownWithTestRenderer function:

export function setupTeardownWithTestRenderer() {
  const context = new SimpleTestContext();
  context.setupBeforeAfter();
  return context;
}

The SimpleTestContext is a class that has some helper methods for setting up tests:

class SimpleTestContext {
  defaultNodeMock = {
    createNodeMock: (element) => {
      if (element.type === 'input') {
        // return document.createElement('input');
        //console.log('createNodeMock got input', element.props);
      }
      if (element.type === 'textarea') {
        // console.log('createNodeMock got textarea', element.props);
        return document.createElement('textarea');
      }
      return null;
    }
  };

  testRenderer = {unmount: () => {}}; // null object

  setup() {
    this.consoleErrorSpy = jest.spyOn(global.console, 'error');
    this.consoleErrorSpy.mockReset();
    Document.prototype.exitFullscreen = jest.fn();
    jest.useFakeTimers();
  }

  tearDown() {
    this.testRenderer.unmount();
    jest.runAllTimers();
    jest.useRealTimers();
    expect(this.consoleErrorSpy).not.toHaveBeenCalled();
  }

  act(func)  {
    TestRenderer.act(func);
  }

  render(jsx, options) {
    this.testRenderer = TestRenderer.create(jsx, options);
    return this.testRenderer;
  }

  renderWithDefaultNodeMock(jsx) {
    return this.render(jsx, this.defaultNodeMock);
  }

  async waitForComponent(component) {
    await waitForExpect(() => expect(
      this.testRenderer.root.findAllByType(component)
        .map(instance => ({ props: instance.props, type: instance.type }))).toHaveLength(1));
    return this.testRenderer.root.findByType(component);
  }

  async waitForComponentByProps(props) {
    await waitForExpect(() => expect(
      this.testRenderer.root.findAllByProps(props)
        .map(instance => ({props: instance.props, type: instance.type}))).toHaveLength(1));
    return this.testRenderer.root.findByProps(props);
  }

  async waitForComponentToLoad(component) {
    const instance = await this.waitForComponent(component);
    await waitForExpect(() => expect(instance.instance.state.hasLoaded).toBeTruthy());
    return instance;
  }

  setupBeforeAfter() {
    beforeEach(() => {
      this.setup();
    });
    afterEach(() => {
      this.tearDown();
    });
  }
}

My problem is that if I run the test where I try to find MenuList for example:

  it('renders menu', () => {
    const menu = renderMenu();
    console.log(menu.instance);
    const menuList = menu.findByType(MenuList);
    console.log(menuList);
  });

I get an error:

Error: No instances found with node type: "undefined"

How can I test what gets rendered with components that use render prop to render jsx?

0

There are 0 best solutions below