TypeError:无法读取未定义(玩笑)的属性'location'

问题描述 投票:0回答:2

我有一个使用来自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();
  });
});

您能告诉我如何解决此问题吗?谢谢。

reactjs unit-testing react-router jestjs enzyme
2个回答
0
投票

问题是您需要指定您正在使用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();
  });
});

Reference.


0
投票

只需将您的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();
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.