繁体   English   中英

类型错误:无法读取未定义的属性“位置”(开玩笑)

[英]TypeError: Cannot read property 'location' of undefined (jest)

我有一个简单的组件,它使用 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(使用 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();
  });
});

以防万一,其他人也面临类似的问题。

我的方法有两个问题。 首先,我在 describe 中使用了 mock(感谢 Johnny 和 MGarcia 帮助我解决这个问题)。

但是,在移动模拟代码后,我又遇到了另一个错误。 错误: React.createElement: type is invalid — expected a string

那是我的另一个 Jest 新手错误,忘记了它的所有底层都是 JavaScript。 使用这种方法,模拟 useLocation 的副作用是react-router-dom中的其余方法不可用。

这是对我有用的方法:

https://github.com/facebook/jest/issues/936#issuecomment-265074320

最终解决方案:

function mockFunction() {
  const original = require.requireActual('react-router-dom');
  return {
    ...original,
    useLocation: jest.fn().mockReturnValue({
      pathname: '/another-route',
      search: '',
      hash: '',
      state: null,
      key: '5nvxpbdafa',
    }),
  };
}

jest.mock('react-router-dom', () => mockFunction());

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

参考。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM