你如何使用浅层测试酶 Reactjs 模拟 useLocation() 路径名? [英] How do you mock useLocation() pathname using shallow test enzyme Reactjs?

查看:25
本文介绍了你如何使用浅层测试酶 Reactjs 模拟 useLocation() 路径名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下标题组件:

import { useLocation } from "react-router-dom";

const Header = () => {
   let route = useLocation().pathname; 
   return route === "/user" ? <ComponentA /> : <ComponentB />;
}

你将如何模拟这个 useLocation() 以获取用户路径?

How will you mock this useLocation() to get the path as user?

我不能简单地在我的测试文件中调用 Header 组件,因为我收到错误:

I cant simply call the Header component as below in my test file as I am getting an error:

TypeError: 无法读取 useLocation 处未定义的属性位置"

TypeError: Cannot read property 'location' of undefined at useLocation

describe("<Header/>", () => {
    it("call the header component", () => {
        const wrapper = shallow(<Header />);
        expect(wrapper.find(ComponentA)).toHaveLength(1);
    });
});

我试过看起来类似于链接如何测试组件使用新的反应路由器钩子?但它没有用.

I have tried looking similar to the link How to test components using new react router hooks? but it didnt work.

我尝试过如下:

const wrapper = shallow(
      <Provider store={store}>
        <MemoryRouter initialEntries={['/abc']}>
          <Switch>
            <AppRouter />
          </Switch>
        </MemoryRouter>
      </Provider>,
    );
    jestExpect(wrapper.find(AppRouter)
      .dive()
      .find(Route)
      .filter({path: '/abc'})
      .renderProp('render', { history: mockedHistory})
      .find(ContainerABC)
    ).toHaveLength(1);

来自链接使用浅渲染测试反应路由器 但它没有用.

from the link Testing react-router with Shallow rendering but it didnt work.

请告诉我.

提前致谢.

推荐答案

我知道这不是您问题的直接答案,但是如果您想要测试浏览器位置或历史记录,您可以使用 挂载并在最后添加一个额外的Route,您可以在其中捕获"历史和位置对象.

I know this isn’t a direct answer to your question, but if what you want is to test the browser location or history, you can use mount and add an extra Route at the end where you can "capture" the history and location objects.

test(`Foobar`, () => {
  let testHistory
  let testLocation

  const wrapper = mount(
    <MemoryRouter initialEntries={[`/`]}>
      <MyRoutes />
      <Route
        path={`*`}
        render={routeProps => {
          testHistory = routeProps.history
          testLocation = routeProps.location
          return null
        }}/>
    </MemoryRouter>
  )

  // Manipulate wrapper

  expect(testHistory)...
  expect(testLocation)...
)}

这篇关于你如何使用浅层测试酶 Reactjs 模拟 useLocation() 路径名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆