Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing useLocation() in React Testing Library

In my component that I want to test I use useLocation hook. In the component I have:

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

  return <div > Welcome < /div>
}

To test the component I wrote this test:

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();
    });
})

Trying this I get TypeError: (0 , _reactRouterDom.useLocation) is not a function. Why do I get this error? How to write the test correctly to avoid the error?

like image 458
Asking Avatar asked May 06 '26 18:05

Asking


2 Answers

You'd better don't mock react-router-dom and the implementation of useLocation hook. Instead, you should use MemoryRouter wrap your component with initialEntries for testing:

An array of locations in the history stack. These may be full-blown location objects with { pathname, search, hash, state } or simple string URLs.

E.g. 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>
    );
  });
});

result:

 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
like image 141
slideshowp2 Avatar answered May 08 '26 08:05

slideshowp2


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

This is how I implemented and it worked for me.

like image 22
Manik Kumar Avatar answered May 08 '26 08:05

Manik Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!