Testing a dropdown with Jest and React

Viewed 1389

I'm currently developing an app using React and I'm having problems writing the tests. I have this dropdown:

<DropdownButton variant="light" key={friend+"dropdown"} data-testid={friend+"dropdown"} title=""> 
   <Dropdown.Item target="_blank" href={friend} key={friend+"dropdownI1"} data-testid={friend+"dropdownI1"}>{t('manageFriends.viewProfile')}</Dropdown.Item>
   <Dropdown.Item onClick={(event) => deleteFriend(event,friend, webId)} key={friend+"dropdownI2"} data-testid={friend+"dropdownI2"}>{t('manageFriends.delete')}</Dropdown.Item>
   <Dropdown.Item onClick={(event) => viewRoutes(event,friend)} key={friend+"dropdownI3"} data-testid={friend+"dropdownI3"}>{t('manageFriends.viewRoutes')}</Dropdown.Item>
</DropdownButton>

and I tried to test that when you click on the DropdownButton the items appear:

test('Dropdown works', () =>{
  expect(getByTestId(friend+'dropdown')).toBeTruthy();
  fireEvent.click(getByTestId(friend+'dropdown'));
  expect(getByTestId(friend +'dropdownI1')).toBeTruthy();   
  expect(getByTestId(friend +'dropdownI2')).toBeTruthy();   
  expect(getByTestId(friend +'dropdownI3')).toBeTruthy();   
});

The test always finds the DropdownButton but never the Items.

I'm using these two libraries: react-testing-library and @testing-library/jest-dom/. I'm also using a bootstrap dropdown:

import DropdownButton from 'react-bootstrap/DropdownButton';

Thank you in advance.

2 Answers

Follow the steps to get the item for DropdownButton:

  1. Add title to DropdownButton. eg:
<DropdownButton title="Friends" variant="light" key={friend+"dropdown"} data-testid={friend+"dropdown"} > 
   <Dropdown.Item target="_blank" href={friend} key={friend+"dropdownI1"} data-testid={friend+"dropdownI1"}>{t('manageFriends.viewProfile')}</Dropdown.Item>
   <Dropdown.Item onClick={(event) => deleteFriend(event,friend, webId)} key={friend+"dropdownI2"} data-testid={friend+"dropdownI2"}>{t('manageFriends.delete')}</Dropdown.Item>
   <Dropdown.Item onClick={(event) => viewRoutes(event,friend)} key={friend+"dropdownI3"} data-testid={friend+"dropdownI3"}>{t('manageFriends.viewRoutes')}</Dropdown.Item>
</DropdownButton> 
  1. Fire event based on title of DropdownButton.
fireEvent.click(screen.getByText("Friends"));

Voila, you will get the list of items.

Here your mistake is that the friend variable in testing file should be a string value that you have not defined and that is why the runtime value of data-testid dosent match.

So instead of using freind give it the value that is there at the runtime.

Related