我有一个简单的组件,它使用来自 React Router 的 useLocation 钩子(Hook)。
//应用程序.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(使用 jest mock)
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();
});
});
你能告诉我如何解决这个问题吗?谢谢。
最佳答案
只需移动您的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();
});
});
关于reactjs - 类型错误 : Cannot read property 'location' of undefined (jest),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60233907/