如何使用反应测试库测试使用 props.history 的按钮,因为它是 onClick?
How can I test a button which uses props.history for it's onClick with react testing library?
这是组件中的按钮,当用户点击它时使用 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}`)}
我怎样才能完成这项工作并解决这个错误,以便我可以测试使用道具的按钮的 onClick 功能?
通过此代码解决了此错误:
const historyMock = { push: jest.fn() };
render(<Home history={historyMock} />);
这是组件中的按钮,当用户点击它时使用 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}`)}
我怎样才能完成这项工作并解决这个错误,以便我可以测试使用道具的按钮的 onClick 功能?
通过此代码解决了此错误:
const historyMock = { push: jest.fn() };
render(<Home history={historyMock} />);