Jest.js 测试React测试库中的useLocation()

oxf4rvwz  于 2023-01-06  发布在  Jest
关注(0)|答案(2)|浏览(260)

在我想要测试的组件中,我使用了useLocation钩子。在组件中,我有:

function Test() {
  const history = useHistory();
  const location = useLocation();
  const query = new URLSearchParams(location.search).get('value');

  return <div > Welcome < /div>
}

为了测试该组件,我编写了以下测试:

jest.mock('react-router-dom', () => ({
    useLocation: jest.fn().mockReturnValue({
        pathname: '',
        search: 'value',
        hash: '',
        state: null,
        key: '5nvxpbdafa',
    }),
}));

jest.mock('react-router-dom', () => ({
    useHistory: () => jest.fn().mockReturnValue({
        push: jest.fn(),
    }),
}));

describe(' page test', () => {
    test('should render', () => {
        render(<Test />);
        const title = screen.getByText(/welcome/i);

        expect(title).toBeInTheDocument();
    });
})

尝试这个我得到TypeError: (0 , _reactRouterDom.useLocation) is not a function。为什么我得到这个错误?如何正确地编写测试以避免错误?

knpiaxh1

knpiaxh11#

你最好不要模仿react-reouter-domuseLocation钩子的实现,而应该用MemoryRouter把你的组件用initialEntries Package 起来进行测试:
历史堆栈中的位置数组。这些可能是具有{ pathname,search,hash,state }或简单字符串URL的成熟位置对象。
例如index.tsx

import React from 'react';
import { useLocation } from 'react-router-dom';

export function Test() {
  const location = useLocation();
  const query = new URLSearchParams(location.search).get('value');
  console.log('query: ', query);

  return <div> Welcome </div>;
}

index.test.tsx

import { render } from '@testing-library/react';
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { Test } from './';

describe('68248240', () => {
  it('should pass', () => {
    render(
      <MemoryRouter initialEntries={[{ pathname: '/', search: '?value=teresa_teng' }]}>
        <Test />
      </MemoryRouter>
    );
  });
});

结果:

PASS  examples/68248240/index.test.tsx (10.807 s)
  68248240
    ✓ should pass (34 ms)

  console.log
    query:  teresa_teng

      at Test (examples/68248240/index.tsx:7:11)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.903 s
nfg76nw0

nfg76nw02#

<Provider store={mockStore}>
    <MemoryRouter initialEntries={[{ pathname: '/Admin/NotificationPreferences' }]}>
      <NotificationPreferences />
    </MemoryRouter>
  </Provider

这就是我如何实施的,它对我很有效。

相关问题