Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write test cases for tabs in Material UI using react testing library?

I am using Material UI tabs in my application and using react testing library. I need to write test cases which for navigating from one tab to another one. Can anybody help me with this, since the code below is not properly working. Thanks in advance.

Code:

const [value, setValue] = React.useState(0)

function handleChange(event, newValue) {
  setValue(newValue)
}
<AntTabs value={value} onChange={handleChange} aria-label="Unit information">
  <AntTab label="HELLOW1" {...unitTabProps(0)} />
  <AntTab label="HELLOW2" {...unitTabProps(1)} />
  <AntTab label="HELLOW3" {...unitTabProps(2)} />
  <AntTab label="HELLOW4" {...unitTabProps(3)} />
  <AntTab label="HELLOW5" {...unitTabProps(4)} />
</AntTabs>
like image 671
Gowtham Manthena Avatar asked Jun 08 '26 07:06

Gowtham Manthena


1 Answers

I believe material ui tabs have attribute of role="tab". By saying that You can then try getting the tab by role. See https://testing-library.com/docs/queries/byrole

In your case you can try this:

const tab = screen.getByRole('tab', { name: 'HELLOW2' });
fireEvent.click(tab);
expect(screen.getByRole('tab', { selected: true })).toHaveTextContent('HELLOW2');
like image 51
Dan Joseph Palisoc Avatar answered Jun 10 '26 22:06

Dan Joseph Palisoc