How to write test cases for tabs in material-ui using react testing library

Viewed 3696

I am using Material UI tabs in my application and using react testing library. I need to write test cases which should be in a way that I need to move from one tab to another tab. I am providing the code below. Can anybody help me with this? 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>
3 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');

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.

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");
})
Related