首页 > 解决方案 > 如何正确模拟 useLocation?

问题描述

我有一个使用 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 />);
  });
});

我在运行测试时收到此错误, TypeError: Cannot read property 'location' of undefined

标签: javascriptreactjsjestjsenzyme

解决方案


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

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

推荐阅读