【发布时间】: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>
在包装器的根节点上模拟事件。它必须是单节点包装器。
这就是文档所说的。也许我在这里遗漏了一些东西。
【问题讨论】: