测试fireEvent之后在无线电组组件中是否仅选择了1个单选按钮。单击react-testing-library

时间:2019-07-02 11:17:31

标签: reactjs testing jestjs react-testing-library

我想测试fireEvent.click单选按钮后仅单击了1个单选按钮。

到目前为止,我仅尝试获取所有单选按钮并寻找代码以检查如果仅选中单选按钮则如何计数。

it("should check if only 1 radiobutton was clicked", () => { 
    const handleChange = jest.fn();
    const { container } = render(
      <React.Fragment>
        <Radiobutton onClick={handleChange} isChecked label="Dummy Radio1" />
        <Radiobutton
          onClick={handleChange}
          isChecked={false}
          label="Dummy Radio2"
        />
        <Radiobutton
          onClick={handleChange}
          isChecked={false}
          label="Dummy Radio3"
        />
      </React.Fragment>
    );
    const dialogContainer = getAllByRole(container, "radio");
    dialogContainer[0].setAttribute("aria-checked", "true");
    dialogContainer.forEach(key => {
      // 
      // Code to check if only 1 radiobutton was clicked
      // 
    });
}); 

我的radiobutton.js

<div
      className="radiobutton"
      role="radio"
      onClick={onClick}
      onKeyDown={onKeyPress}
      aria-checked={isChecked}
      tabIndex={0}
      value={label}
    >
      <span className="radiobutton__label">{label}</span>
    </div>

1 个答案:

答案 0 :(得分:2)

您可以使用fireEvent,然后将.checkedfilter一起使用,如下所示:

it("should click on text", () => { 
    const handleChange = jest.fn();
    const { container } = render(<Radiogroup onClick={handleChange} />);
    const dialogContainer = getAllByRole(container, "radio");

    const checkedItemsBeforeClick = dialogContainer.filter(el=>el.checked)
    expect(checkedItems.length).toEqual(0)
    fireEvent.click(dialogContainer[0]);

    const checkedItemsAfterClick = dialogContainer.filter(el=>el.checked)
    expect(checkedItems.length).toEqual(1)
}); 

更新:

由于您没有使用input元素,因此需要执行以下操作:

const RadioButtonGroup ()=>{
 const [selectedId, setSelectedId] = useState('select_1')
 const handleChange = (ev)=>{
     setSelectedId(ev.target.id)
 }
return (
<React.Fragment>
    <Radiobutton id="select_1 onClick={handleChange} isChecked={selectedId==="select_1"} label="Dummy Radio1" />
    <Radiobutton
      onClick={handleChange}
      isChecked={selectedId==="select_2"} 
      label="Dummy Radio2"
    />
    <Radiobutton
      onClick={handleChange}
      isChecked={false}
      label="Dummy Radio3"
      isChecked={selectedId==="select_2"} 
    />
  </React.Fragment>
)
};

并确保将id属性传递到Radiobutton中。希望有帮助。