【问题标题】:How to mock useLocation correctly?如何正确模拟 useLocation?
【发布时间】: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:无法读取未定义的属性“位置”

【问题讨论】:

标签: javascript reactjs jestjs enzyme


【解决方案1】:

尝试将 useLocation 模拟为 jest.fn().mockImplementation

jest.mock('react-router', () => ({
...jest.requireActual("react-router") as {},
   useLocation: jest.fn().mockImplementation(() => {
    return { pathname: "/testroute" };
   })
}));

【讨论】:

  • 工作得很好,谢谢
【解决方案2】:

以下是我在测试中是如何做到这一点的。 * 注意我使用的是打字稿

import routeData from 'react-router';    

    describe('Login Page UnitTests', () => {
      const useLocation = jest.spyOn(routeData, 'useLocation');
    
      beforeEach(() => {
        useLocation.mockReturnValue({ search: 'testQueryParameters'} as any);
      });

      // Add unit tests
    }

确保清除模拟以避免在后续测试中出现数据问题

【讨论】:

    猜你喜欢
    • 2020-08-10
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 2018-09-25
    • 1970-01-01
    相关资源
    最近更新 更多