【发布时间】:2021-08-30 01:12:49
【问题描述】:
我有一个组件使用 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:无法读取未定义的属性“位置”
【问题讨论】:
-
我建议你不要模拟它,将组件安装在例如用于测试目的的 MemoryRouter 或创建历史记录;见stackoverflow.com/a/65275037/3001761,reactrouter.com/web/guides/testing
标签: javascript reactjs jestjs enzyme