【问题标题】:How can I simulate click event with enzyme?如何用酶模拟点击事件?
【发布时间】:2020-02-26 17:16:28
【问题描述】:

我想模拟单击将 currentPageIndex 设置为 currentPageIndex - 1 并将先前状态与当前状态匹配的按钮。 模拟方法不起作用。

it("sets state when previous button clicked", () => {
      const randomProps = randomPaginationProps();
      const wrapper = setup(Pagination, randomProps);
      const componentState = wrapper.state();
      const prevButton = findByTestAttribute(wrapper, "prev");
      console.log(componentState.currentPageIndex);
      prevButton.simulate("click");
      // outputs the same currentPageIndex as above console.log
      console.log(componentState.currentPageIndex);
    });

//helper methods in different file
export const setup = (Component, props = {}, state = null) => {
  const wrapper = shallow(<Component {...props} />);
  if (state) wrapper.setState(state);
  return wrapper;
};

export const findByTestAttribute = (wrapper, val) => {
  return wrapper.find(`[data-test="${val}"]`);
};
// return method of rendered component
return (
      <div data-test="pagination" className="pagination">
        <button
          data-test="prev"
          className="change-page-btn"
          onClick={() => this.changePageButtonHandler("prev")}
          disabled={currentPageIndex === 0}
        >
          Prev
        </button>
        {pagination}
        <button
          data-test="next"
          className="change-page-btn"
          onClick={() => this.changePageButtonHandler("next")}
          disabled={currentPageIndex === pages.length - 1}
        >
          Next
        </button>
      </div>
    );
  }
}

console.log(prevButton.debug()) 时,显示如下输出。所以按钮在那里,可以这么说。

 <button data-test="prev" className="change-page-btn" onClick={[Function: onClick]} disabled={false}>
      Prev
    </button>

在包装器的根节点上模拟事件。它必须是单节点包装器。

这就是文档所说的。也许我在这里遗漏了一些东西。

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    试试:

    prevButton.prop("onClick")();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-18
      • 2018-11-05
      • 2018-12-07
      • 2018-02-24
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      相关资源
      最近更新 更多