如何正确模拟useLocation?

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

我有一个使用 useLocation 挂钩从 URL 获取路径的组件。

const { pathname } = useLocation();
useEffect(() => { }, [pathname]);

当我尝试使用 来模拟该位置时,

import React from 'react';
import ExampleComponent from './ExampleComponent';
import { fireEvent, render } from '@testing-library/react';
import { shallow } from 'enzyme';

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useLocation: () => ({
    pathname: 'https://URL/'
  })
}));

describe('<ExampleComponent />', () => {
  it('should render correctly', () => {
    shallow(<ExampleComponent />);
  });
});

我在运行测试时遇到此错误, 类型错误:无法读取未定义的属性“位置”

javascript reactjs jestjs enzyme
4个回答
4
投票

尝试将 useLocation 模拟为 jest.fn().mockImplementation

jest.mock('react-router', () => ({
...jest.requireActual("react-router") as {},
   useLocation: jest.fn().mockImplementation(() => {
    return { pathname: "/testroute" };
   })
}));

3
投票

以下是我在测试中如何做到这一点的。 *注意我正在使用打字稿

import routeData from 'react-router';    

    describe('Login Page UnitTests', () => {
      const useLocation = jest.spyOn(routeData, 'useLocation');
    
      beforeEach(() => {
        useLocation.mockReturnValue({ search: 'testQueryParameters'} as any);
      });

      // Add unit tests
    }

确保清除模拟以避免后续测试中的数据问题


1
投票

mock

useLocation
的正确方法如下:

import React from 'react';
import ExampleComponent from './ExampleComponent';
import { fireEvent, render } from '@testing-library/react';
import { MemoryRouter} from 'react-router-dom';
import { shallow } from 'enzyme';

const renderComponent = () => {
  return (
      <MemoryRouter
          initialEntries={["/one", "/two", { pathname: 'https://URL/' }]}
          initialIndex={1}>
         <ExampleComponent />
     </MemoryRouter>
   );
}

describe('<ExampleComponent />', () => {
  it('should render correctly', () => {
    shallow(renderComponent());
  });
});

0
投票

这对我有用

import * as router from 'react-router';

    jest
      .spyOn(router, 'useLocation')
      .mockReturnValue({ pathname: '/department/details/1213', search: '', state: {}, hash: '' });
© www.soinside.com 2019 - 2024. All rights reserved.