0

I have a dropdown menu from ant design in my react component (consoliated code below, only showing relevant details): `


                <Select
                  data-testid="addCompany"
                  showSearch
                  style={{ width: '100%' }}
                  onChange={(value) =>
                    onAddCompanySelectHandler(periodIndex, value)
                  }
                  placeholder="Add Company"
                  value={companyDropdownValue}
                  options={companyDropdownList}
                />

`

This is my test that renders component with dropdown and mocked comanies passed to it as props: `

const companyDropdownList = companies; //got this from the mock data

describe('Test BaselineItemDetailsEdit component', () => {
  const onAddCompanySelectHandler = jest.fn();

  const editProps = {
    companyDropdownList,
    onAddCompanySelectHandler
 };

it.only('calls add Company from dropdown', async () => {
  render(<Component {...props} />);
  const company = screen.getByText('Company Name');
  userEvent.click(company);
  expect(onAddCompanySelectHandler).toBeCalled();
});

` I seem to be able to find the company from the dropdown but when click on it function is not being called. I have other regular buttons in this components and test that do call mocked functions though.

`

  ● Test ItemDetails component › calls add Company from dropdown

    expect(jest.fn()).toBeCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

       95 |     const company = screen.getByText('Company Name');
       96 |     userEvent.click(company);
    >  97 |     expect(onAddCompanySelectHandler).toBeCalled();
          |                                       ^
       98 |   });
       99 | });
      100 |

`

I've tried to call mocked function and expected it to be called.

Mike Bely
  • 21
  • 4
  • This may help you:https://stackoverflow.com/questions/55184037/react-testing-library-on-change-for-material-ui-select-component Material UI is painful to test... – Letincel Dec 16 '22 at 16:43

1 Answers1

0

This is how I ended up testing it. Need to get combobox item first with and dropdown:

it('calls Company from dropdown', async () => {
  userEvent.click(screen.getByTestId('toExpand'));
  userEvent.click(screen.getByRole('combobox'));
  userEvent.click(screen.getByText('CompanyName'));

  expect(onAddCompanySelectHandler).toBeCalledWith(0, 'CompanyName');
});
Jax
  • 1,839
  • 3
  • 18
  • 30
Mike Bely
  • 21
  • 4