首页 > 解决方案 > 如何测试与Router连接的React组件?

问题描述

我有这样一个组件

const ButtonWithRouter = ({ to, history, ...restProps }) => (
  <Button
    onClick={() => history.push(to)}
    {...restProps}
  />
);
export default withRouter(ButtonWithRouter)

如您所见,它使用 react-router-dom 并与Router 连接。我的测试看起来像这样

test('render', () => {
    const component = renderer.create(
    <Router>
      <ButtonWithRouter to='/anywhere'>Anywhere</ButtonWithRouter>
    </Router>
  );
    const tree = component.toJSON();

    expect(tree).toMatchSnapshot();
 });

我认为在我的测试中导入和使用真正的路由器是不正确的。如何正确执行?

标签: reactjsreact-routerjestjs

解决方案


推荐阅读