javascript - 如何正确模拟 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
解决方案
尝试将 useLocation 模拟为 jest.fn().mockImplementation
jest.mock('react-router', () => ({
...jest.requireActual("react-router") as {},
useLocation: jest.fn().mockImplementation(() => {
return { pathname: "/testroute" };
})
}));
推荐阅读
- java - 无法在 android 设备/模拟器的 localhost 上发出 http GET 请求
- logic - .gitlab-ci.yml 中的规则条件是否有 AND 选项?
- python - 标记时间序列索引的双胞胎以进行跌落/跳跃
- python - 在一个循环中为变量分配不同的名称?
- c++ - 引用临时成员
- c# - 防止修改缓存对象
- html - 如何使 100% 高度的 div 扩展到 HTML/CSS 中的滚动溢出?
- reactjs - 带有 Sanctum 身份验证的 Laravel 8 (Reactjs SPA)
- c# - 如何使用自定义 XSD 架构编写 XML?
- azure - Runbook 将 Powershell 运行为 azure 帐户