Search code examples
react-nativejestjsreact-native-popup-menu

How to test components with menu


I'm trying to test, with Jest's snapshots, a component containing a menu. The problem is that the menu's content is not rendered so I can't test the whole component.

Is there a way to force a menu to render all its MenuOption? I tried to use <Menu opened={true}>...</Menu> but the result was the same.

For example, this code will produce a snapshot not containing foo.

  expect(renderer.create(
    <MenuContext>
      <Menu>
        <MenuOptions>
          <MenuOption>
            foo
          </MenuOption>
        </MenuOptions>
      </Menu>
    </MenuContext>
  )).toMatchSnapshot();

Solution

  • Menu component does not render MenuOptions directly to overcome problems with react-native z-index handling. Additionally it needs first to get dimensions of it etc. It would require more steps until you got them rendered in your test.

    But the library itself has a lot of tests and in my opinion your test should not depend on internal handling of the library. Instead you should mock it - e.g.

    import 'react-native';
    import React from 'react';
    
    jest.mock('react-native-popup-menu', () => ({
      Menu: 'Menu',
      MenuContext: 'MenuContext',
      MenuOptions: 'MenuOptions',
      MenuOption: 'MenuOption',
      MenuTrigger: 'MenuTrigger',
    }));
    
    import BasicExample from '../BasicExample';
    
    import renderer from 'react-test-renderer';
    
    test('renders correctly', () => {
      const tree = renderer.create(
        <BasicExample />
      ).toJSON();
      expect(tree).toMatchSnapshot();
    });
    

    Note - your mocks and your imports should match! (Menu can be imported in two ways).

    And then you get nice snapshot - see example snapshot