Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test the antd Dropdown with Enzyme

This is the code that I wrote:

import {Dropdown, Menu} from 'antd';
class comp extends Component {
    state = {
      concept: 'Concept',
    }

    menuItemSelection=({key}) => {
      this.setState({
        concept: key
      })
    }

    menu = (
      <Menu onClick={this.menuItemSelection}>
        <Menu.Item key='ab'>ab</Menu.Item>
        <Menu.Item key='mw'>mw</Menu.Item>
        <Menu.Item key='va'>va</Menu.Item>
      </Menu>
   )

    render() {
      const {concept} = this.state
      return (
        <div>
            <Dropdown overlay={this.menu}>
              <div>{concept}</div>
            </Dropdown>
                 </div>
      )
    }
}

export default comp;

This is how my interface currently works:

When I hover over the DropDown the menu will appear and when any of the items are clicked on they get selected and the state variable concept gets updated. How can I test this DropDown? I am not able to access the menu to simulate the 'click' on the menu.

component = mount(<comp />)
    const dropdown = component.find(Dropdown) // this i am able to find 
    const menuInstance = component.find(Menu) // this it is returning reactwrapper {length:0}

How do I simulate the onclick on menu? I tried console logging the dropdown.props().overlay and I got:

sdas { '$$typeof': Symbol(react.element),
      type: 
       { [Function: Menu]
         Divider: { [Function: Divider] propTypes: [Object], defaultProps: [Object] },
         Item: { [Function: MenuItem] contextTypes: [Object], isMenuItem: 1 },
         SubMenu: { [Function: SubMenu] contextTypes: [Object], isSubMenu: 1 },
         ItemGroup: 
          { [Function: MenuItemGroup]
            propTypes: [Object],
            defaultProps: [Object],
            isMenuItemGroup: true },
         defaultProps: 
          { prefixCls: 'ant-menu',
            className: '',
            theme: 'light',
            focusable: false },
         childContextTypes: { inlineCollapsed: [Function], antdMenuTheme: [Function] },
         contextTypes: { siderCollapsed: [Function], collapsedWidth: [Function] } },
      key: null,
      ref: null,
      props: 
       { onClick: [Function],
         children: [ [Object], [Object], [Object] ],
         prefixCls: 'ant-menu',
         className: '',
         theme: 'light',
         focusable: false },
      _owner: null,
      _store: {} }
like image 210
aravind_reddy Avatar asked Jun 29 '18 16:06

aravind_reddy


1 Answers

This is how I achieved it:

// Let's assume you already have a ShallowWrapper with some Dropdown's parent.
const dropdown = wrapper.find(Dropdown);
const submenu = shallow(<div>{dropdown.prop('overlay')}</div>);
const submenuItems = submenu.find(Menu.Item);
submenuItems.forEach(item => item.simulate('click'));
like image 197
Jordi Nebot Avatar answered Oct 14 '22 08:10

Jordi Nebot