6

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>
axel
  • 3,778
  • 4
  • 45
  • 72
Gowtham Manthena
  • 199
  • 5
  • 21

3 Answers3

13

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');
  • I like this. This is testing the **behaviour**. Other solutions seem to be testing the **implementation**. You can also do something like this to check for accessible name: `expect(screen.getByRole('tab', { selected: true })).toHaveAccessibleName('Tab 2');` – vighnesh153 May 05 '22 at 13:28
3

Here is a test to check that the second tab becomes selected when we click on it:

it("activates second tab when clicking on it", () => {
  const { getByText } = render(<YourComponent />);
  const hellow1 = getByText("HELLOW1").closest("button");
  const hellow2 = getByText("HELLOW2").closest("button");
  expect(hellow1).toHaveAttribute("aria-selected", "true");
  expect(hellow2).toHaveAttribute("aria-selected", "false");
  fireEvent.click(hellow2);
  expect(hellow1).toHaveAttribute("aria-selected", "false");
  expect(hellow2).toHaveAttribute("aria-selected", "true");
});

You probably will not need to do this test because Material UI tabs are already tested, but you can ispire from the code to test your features.

Roman Mkrtchian
  • 2,548
  • 1
  • 17
  • 24
1

It worked for me like this:

it("activates second tab when clicking on it", () => {
    render(<YourComponent />)

    const HELLOW1 = screen.getByText("HELLOW1").closest("button");
    const HELLOW2 = screen.getByText("HELLOW2").closest("button");
            
    expect(HELLOW1).toHaveAttribute("aria-selected", "true");
    expect(HELLOW2).toHaveAttribute("aria-selected", "false");

    fireEvent.click(FAQs);
    expect(HELLOW1).toHaveAttribute("aria-selected", "false");
    expect(HELLOW2).toHaveAttribute("aria-selected", "true");
})
axel
  • 3,778
  • 4
  • 45
  • 72
Ivan K.
  • 748
  • 7
  • 11