我有一个使用来自React Router的useLocation钩子的简单组件。
// App.jsx
import React from 'react';
import { useLocation } from 'react-router-dom';
function App() {
const location = useLocation();
const pathName = location.pathname;
useEffect(() => {
// Use pathName here
}, [pathName]);
}
// App.test.js
import App from './App';
describe('App component', () => {
it('Renders correctly', () => {
const wrapper = shallow(<App />);
expect(wrapper).toMatchSnapshot();
});
});
//更新App.test.js(带有开玩笑的模拟)
import App from './App';
describe('App component', () => {
jest.mock('react-router-dom', () => ({
useLocation: jest.fn().mockReturnValue({
pathname: '/another-route',
search: '',
hash: '',
state: null,
key: '5nvxpbdafa',
}),
}));
it('Renders correctly', () => {
const wrapper = shallow(<App />);
expect(wrapper).toMatchSnapshot();
});
});
您能告诉我如何解决此问题吗?谢谢。
问题是您需要指定您正在使用es6模块语法。试试这个:
import App from './App';
jest.mock('react-router-dom', () => ({
__esModule: true,
useLocation: jest.fn().mockReturnValue({
pathname: '/another-route',
search: '',
hash: '',
state: null,
key: '5nvxpbdafa',
}),
}));
describe('App component', () => {
it('Renders correctly', () => {
const wrapper = shallow(<App />);
expect(wrapper).toMatchSnapshot();
});
});
只需将您的jest.mock
声明移到文件顶部,它应该可以工作:
import App from './App';
jest.mock('react-router-dom', () => ({
useLocation: jest.fn().mockReturnValue({
pathname: '/another-route',
search: '',
hash: '',
state: null,
key: '5nvxpbdafa',
}),
}));
describe('App component', () => {
it('Renders correctly', () => {
const wrapper = shallow(<App />);
expect(wrapper).toMatchSnapshot();
});
});