Unable to find only Button Component for test

I have the following component and trying to perform tests on it.

I am able to find all other Components such as Element and Table.

But there is no result for finding Button object even though there are 2 of those.

Why is that the case?

To note Button, Element and Table component here are all custom components of mine.

Component being tested

export const MyComponent = () => (
  <div>
    <div style={{ margin: 20 }}>
      <Button onClick={() => {}}>
        Click Me!
      </Button>
      <Button onClick={() => {}}>
        Click Me!
      </Button>
    </div>

    <Element name="name">
      title
    </Element>
    <div>
      <Table name="name" />
    </div>
  </div>
);

export default MyComponent;

My test

describe('test page', () => {

     it('should click', () => {

    const mockSelectorToggle = jest.fn();
    const defaultProps = {};
    const initialise = props => shallow(<MyComponent {...defaultProps} {...props} />);
    const wrapper = initialise();

    // all the following found
    wrapper.find('div')
    wrapper.find('div').find('div')
    wrapper.find('Element')
    wrapper.find('Table')

    // nothing found. Why only Button not findable?
    // wrapper.find('Button')
    // wrapper.find('div').find('div').find('Button')

    // looking to test it this way
    wrapper.find('Button').first().simulate('click');
    expect(mockSelectorToggle).toHaveBeenCalled();
  });
});

2 thoughts on “Unable to find only Button Component for test”

  1. Well according to the Enzyme documentation, there are various selectors available, in particular, this

    https://enzymejs.github.io/enzyme/docs/api/selector.html#1-a-valid-css-selector

    and this

    https://enzymejs.github.io/enzyme/docs/api/selector.html#2-a-react-component-constructor

    Now the issue seems to be related to what explained here:

    React component name and props (Button, Button[type="submit"], etc) – however, please note that it is strongly encouraged to find by component constructor/function and not by display name.

    My impression is that the selector is searching for the HTML button tag and not for your actual Button component.

    My suggestion is to change your code in this way:

    wrapper.find(Button);
    

    So basically do what the documentation recommend: "find by component constructor/function and not by display name".

    Reply

Leave a Comment