【问题标题】:How to write test cases for tabs in material-ui using react testing library如何使用反应测试库为 Material-ui 中的选项卡编写测试用例
【发布时间】:2021-01-27 16:39:16
【问题描述】:

我在我的应用程序中使用 Material UI 选项卡并使用反应测试库。我需要编写测试用例,这应该是我需要从一个选项卡移动到另一个选项卡的方式。我提供下面的代码。有人可以帮我吗?提前致谢。

代码:

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>

【问题讨论】:

    标签: reactjs material-ui react-testing-library


    【解决方案1】:

    这是一个测试,检查当我们单击第二个选项卡时它是否被选中:

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

    您可能不需要进行此测试,因为 Material UI 选项卡已经过测试,但您可以从代码中获取灵感来测试您的功能。

    【讨论】:

      【解决方案2】:

      我相信材质 ui 选项卡具有 role="tab" 的属性。通过说您可以尝试按角色获取选项卡。见https://testing-library.com/docs/queries/byrole

      在你的情况下,你可以试试这个:

      const tab = screen.getByRole('tab', { name: 'HELLOW2' });
      fireEvent.click(tab);
      expect(screen.getByRole('tab', { selected: true })).toHaveTextContent('HELLOW2');
      

      【讨论】:

        【解决方案3】:

        这样对我有用:

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

        【讨论】:

          猜你喜欢
          • 2020-04-26
          • 1970-01-01
          • 2022-10-19
          • 1970-01-01
          • 2021-05-09
          • 2020-03-02
          • 1970-01-01
          • 2020-07-07
          • 1970-01-01
          相关资源
          最近更新 更多