【问题标题】:React Jest Enzyme change Material UI CheckboxReact Jest Enzyme 更改 Material UI 复选框
【发布时间】:2022-01-05 05:42:39
【问题描述】:

我想在 React with Jest/Enzyme 中测试使用 Material UI 制作的复选框。

我可以轻松测试一些文本,但找不到复选框并更改状态。

复选框:

  <FormControlLabel
            control={
              <Checkbox
                data-testid={x.label}
                ...

测试:

describe("Jobs Filtering2", () => {
  it("Set data", () => {
 
    const TestComp = () => {

      // Context imports
      const {
      ...
      } = useContext(JobsContext);

      useEffect(() => {
       ...
      }, []);
    
      return <Jobs />;
    };

    const wrapper = mount(
      // User data
      <UserContext.Provider value={{ userData: userData }}>
        <JobsContextProvider>
          <TestComp />
        </JobsContextProvider>
      </UserContext.Provider>
    );

    // Find in UI
    // Read the total jobs
    expect(wrapper.find(`.jobs-header__sub`).text()).toEqual(
      `We have in total ${JobsDb.length}!`
    );

    // Find The filter jobs column
    expect(wrapper.find(`[data-testid="filter-title-desktop"]`).text()).toEqual(
      "Filter Jobs"
    );

// ERROR
   wrapper
      .find(`[data-testid="Marketing"]`)
      .simulate("change", {
        target: { checked: true },
      });
  });

然后报错:

 Method “simulate” is meant to be run on 1 node. 7 found instead.

有什么想法吗? 哪里出错了?

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    如果有人偶然发现这个问题,解决方案:

      wrapper
            .find('input[type="checkbox"]')
            .find("#id-checkbox"); 
    

    模拟点击:

    wrapper
                .find('input[type="checkbox"]')
                .find("#id-checkbox").simulate("change", {
          target: {
            checked: true,
    ... others if you need
                  },
                 });
    

    改变状态:

    wrapper
                .find('input[type="checkbox"]')
                .find("#id-checkbox")
                .checked = true
    

    【讨论】:

      猜你喜欢
      • 2019-07-24
      • 2020-08-15
      • 1970-01-01
      • 2021-01-31
      • 2019-08-30
      • 2022-08-13
      • 1970-01-01
      • 2020-05-10
      • 2020-09-29
      相关资源
      最近更新 更多