首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用withRouter和connect,如何在酶中断言调用了history.push?

使用withRouter和connect,可以在酶中断言调用了history.push的方式如下:

  1. 首先,确保你的组件已经使用了withRouter进行包装,以便能够访问到路由相关的属性和方法。
代码语言:txt
复制
import { withRouter } from 'react-router-dom';

class YourComponent extends React.Component {
  // ...
}

export default withRouter(YourComponent);
  1. 然后,在测试文件中,使用enzyme的shallow函数来渲染你的组件,并使用jest.fn()创建一个mock函数来模拟history.push方法。
代码语言:txt
复制
import { shallow } from 'enzyme';
import { createMemoryHistory } from 'history';

// 导入你的组件
import YourComponent from './YourComponent';

describe('YourComponent', () => {
  it('should call history.push when something happens', () => {
    const history = createMemoryHistory();
    const pushMock = jest.fn();
    history.push = pushMock;

    // 使用shallow渲染组件
    const wrapper = shallow(<YourComponent />, {
      context: { router: { history } },
    });

    // 模拟触发某个事件或条件
    // ...

    // 断言history.push被调用
    expect(pushMock).toHaveBeenCalledWith('/your-path');
  });
});

在这个例子中,我们使用了enzyme的shallow函数来浅渲染组件,并通过context属性传递了模拟的history对象。然后,我们创建了一个mock函数pushMock来模拟history.push方法,并将其赋值给history对象。最后,在断言部分,我们使用expect语句来验证history.push是否被调用,并传入了预期的路径参数。

需要注意的是,这里使用了createMemoryHistory来创建一个内存中的history对象,以便在测试中模拟路由的跳转。另外,如果你的组件中使用了connect函数来连接Redux的状态和操作,也需要确保在测试文件中正确地配置Provider和store。

希望以上内容能够帮助到你!如果有任何疑问,请随时提问。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券