0

Lets' say I have a component below

import { Menu } from 'antd';
...
return (
<Menu>
  <Menu.Item>item 1</Menu.Item>
  <Menu.Item>item 2</Menu.Item>
  <Menu.SubMenu title="sub menu">
    <Menu.Item>item 3</Menu.Item>
  </Menu.SubMenu>
</Menu>
)

I can mock For <Menu/>

jest.mock('antd', () => {
  const MockMenu: FC = (props) => <div data-testid="mock-Menu" {...props} />;
  return { MockMenu };
});

How can I Mock something like <Menu.Item/>?

Since I am getting error when running the test

TypeError: Cannot read properties of undefined (reading 'Item')
CCCC
  • 5,665
  • 4
  • 41
  • 88

1 Answers1

1

You can try something like this:

jest.mock('antd', () => {
  class Menu extends React.Component<{}, {}> {

    static Item = (props) => <div data-testid="mock-Item" {...props} />;

    static SubMenu = (props) => <div data-testid="mock-Submenu" {...props} />;

    render() {
      return (
        <div data-testid="mock-Menu" {...this.props} />
      );
    }
  }
  return { Menu };
});

Or with functional components:

jest.mock('antd', () => {
  let Menu: { (props: {}): React.ReactElement; Item?: FC; SubMenu?: FC; } = (props) => <div data-testid="mock-Menu" {...props} />;
  MockMenu.Item = (props) => <div data-testid="mock-Item" {...props} />;
  MockMenu.SubMenu = (props) => <div data-testid="mock-Submenu" {...props} />;
  
  return { Menu };
});

I can't test it right now, but that should work. The type is a bit tricky though so it might need some tinkering.

David G.
  • 1,255
  • 9
  • 16
  • Is it a must to use class component? – CCCC Aug 04 '22 at 10:57
  • No, not really. I just copied the structure from the antd package, let me update the answer with a functional solution. – David G. Aug 04 '22 at 11:49
  • `Component definition is missing display name` – CCCC Aug 05 '22 at 01:32
  • That's just a lint rule, you can disable the rule in the tests or either give a `displayName` prop to each component or use named functions instead of anonymous functions https://stackoverflow.com/questions/52992932/component-definition-is-missing-display-name-react-display-name . I can update the code if you can't manage. – David G. Aug 05 '22 at 08:13