如何模拟每个测试中不同的 useLocation 的值?

问题描述 投票:0回答:1

我的react组件应该根据当前的位置对状态做一些改变,有一个自定义的钩子,在组件加载时被调用。

有一个自定义的钩子,在组件加载时被调用。useLocation().pathname 和结果在switchcase的正确变化。

这可以是Jest测试在一个filedescribe?jest.mock useLocation 但我就是不能在Jest描述里面做......

const mockUseLocation = () => {
    jest.mock('react-router-dom', () => ({
        useLocation: jest.fn().mockReturnValue({
            pathname: '/val1'
        })
    }))
};

我怎样才能测试所有的开关箱分支?

switch (pathname) {
   case 'val1':
       return 100;
   case 'val2':
       return 200;
   ...
   ...
}
jestjs react-hooks react-router-dom react-component
1个回答
0
投票

最简单的方法是使用 MemoryRouter 反而嘲讽 useLocation. 此外,如果你的组件有 <Link>否则你会得到 "链接不能在路由器外使用 "的错误信息)。同时它还可以让你检查导航是否发生。所以,有了这么多好处,嘲讽 useLocation 直接没有任何价值。

举一反三 在正式文件中。这将是类似的东西。

test("current user is active in sidebar", () => {
  const wrapper = mount(
    <MemoryRouter initialEntries={["/users/2"]}>
      <YourComp />
    </MemoryRouter>
  );
  expected(wrapper.find(User)).toHaveLength(2);
});
© www.soinside.com 2019 - 2024. All rights reserved.