Reactjs 如何用酶模拟点击事件?
我想模拟一下单击按钮,将currentPageIndex设置为currentPageIndex-1,并将以前的状态与当前状态相匹配。 模拟方法不起作用Reactjs 如何用酶模拟点击事件?,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,我想模拟一下单击按钮,将currentPageIndex设置为currentPageIndex-1,并将以前的状态与当前状态相匹配。 模拟方法不起作用 it("sets state when previous button clicked", () => { const randomProps = randomPaginationProps(); const wrapper = setup(Pagination, randomProps); const
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>
);
}
}
在包装器中的根节点上模拟事件。它必须是单节点包装器 医生们就是这么说的。也许我这里遗漏了什么。试试:
prevButton.prop("onClick")();
prevButton.prop("onClick")();