javascript - 如何正确模拟 useLocation?

标签 javascript reactjs jestjs enzyme

我有一个使用 useLocation 钩子(Hook)从 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 />);
  });
});
我在运行测试时收到此错误,
类型错误:无法读取未定义的属性“位置”

最佳答案

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

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

关于javascript - 如何正确模拟 useLocation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67965012/

相关文章:

Vue.js 用 Jest 进行测试,类绑定(bind)失败

reactjs - 如何让 Jest 在等待断言之前等待所有异步代码完成执行

javascript - 无法获取最接近的上一个 td 输入的值

javascript - webpack:配置文件中 [ext] 之后的问号

javascript - 在 React 中隐藏 HTML 元素

reactjs - Karma + Browserify + Jasmine + Istanbul + React 覆盖范围

php - 防止在拖动时显示图像

javascript - NIC 和用户名验证字段

javascript - 在 React JS 上绑定(bind) touchstart 的正确方法是什么?

javascript - Jest/ react - TypeError : Cannot read property 'touchStart' of undefined