Home > Software design >  Unable to find the element with data-testid in list rendering in react
Unable to find the element with data-testid in list rendering in react

Time:07-08

Currently, the project I am developing is ReactJs - Vite. I am following the docs for react-testing-library to find if the element with data-testid attribute is rendered or not.

The react-testing-library cannot find the element even though it exists.

My Test


it('should render option destination', () => {
    render(<Search destinations={[{ id: 1, name: 'Test' }]} />);
    expect(screen.getAllByTestId('option-search-destination')).toBeInTheDocument();
});

My Component


...
<Select
  className="search-form__item__field"
  allowClear
  bordered={false}
  style={{ border: 'none' }}
  placeholder={t('search.destination.place_holder')}
  showArrow>
  <OptGroup label="All destinations">
    {destinations &&
      destinations.map((item, index) => (
        <>
          <Option
            key={index}
            value={item.id}
            data-testid="option-search-destination">
            {item.name}
          </Option>
        </>
      ))}
  </OptGroup>
</Select>
...

Test Error

TestingLibraryElementError: Unable to find an element by: [data-testid="option-search-destination"]

CodePudding user response:

It looks like the component you are trying to test is a select. By default, the Select's menu will be closed so the options are not rendered and react-testing-library can't find the options of the select component.

In order for you to be able to target them you need to open the menu of the select component. Assuming it is done by clicking on it, you can either use react testing library's native fireEvent, or alternatively use userEvent which is a companion library to react-testing-library which they recommend to use user-event

Assuming you are using userEvent you will need to target your select and apply a click event on it to open the menu. Then the select menu will open and you will be able to query the options within it.

it('should render option destination', () => {
    render(<Search destinations={[{ id: 1, name: 'Test' }]} />);
    const select = screen.getByTestId('my-select');
    userEvent.click(select);

    const options = screen.getAllByTestId('option-search-destination')
    expect(options).toBeInTheDocument();
});
  • Related