这是组件中的按钮,当用户单击它时会使用props.history。
<button data-testid="btn" onClick={ () => props.history.push(`/post/${value}`) } >Search</button>
我尝试像这样测试onClick:
test('Button should navigate the url when enabled', () => {
render(<Home />);
const btn = screen.getByTestId('btn');
fireEvent.click(btn);
});
但是它抛出一个错误,即:
TypeError: Cannot read property 'push' of undefined
> 21 | onClick={() => props.history.push(`/post/${value}`)}
我该如何工作并解决此错误,以便可以测试使用onprop函数的道具的按钮?
答案 0 :(得分:0)
通过以下代码解决了该错误:
const historyMock = { push: jest.fn() };
render(<Home history={historyMock} />);