Home > Back-end >  Testing component reaction to location change
Testing component reaction to location change

Time:07-22

I have a code example

const Component = () => {
  const location = useLocation();
  const tracking = useTracking();

  useEffect(() => {
    tracking.trackPageView(...);
  }, [location, tracking]);

  return (<div/>)
}

In my tests I would like to test that my trackPageView method is being called on every location change.

const { rerender } = render(
  <MemoryRouter initialRouterEntries=['/']><Component></MemoryRouter>
)

rerender(
  <MemoryRouter initialRouterEntries=['/new-location']><Component></MemoryRouter>
)

// expect(mockTracking).toHaveBeen....

But for some reason location from useLocation doesn't change, therefore it doesn't trigger the useEffect execution for the second time.

Is it connected to MemoryRouter? Should I use BrowserRouter instead? Or maybe use something different than useLocation?

CodePudding user response:

Using createMemoryHistory create a memory history and pass it to the <Router /> component will do the work. Using the history.push() method to change the history stack.

E.g.

index.tsx:

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

export const MyComponent = () => {
  const location = useLocation();
  useEffect(() => {
    console.log('location: ', location);
  }, [location]);

  return <div />;
};

index.test.tsx:

import { render } from '@testing-library/react';
import React from 'react';
import {  Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import { MyComponent } from '.';

describe('73035199', () => {
  test('should pass', () => {
    const history = createMemoryHistory();
    history.push('/');
    render(
      <Router history={history}>
        <MyComponent />
      </Router>
    );
    history.push('/new-location');
  });
});

Test result:

 PASS  stackoverflow/73035199/index.test.tsx (10.807 s)
  73035199
    ✓ should pass (41 ms)

  console.log
    location:  {
      pathname: '/',
      search: '',
      hash: '',
      state: undefined,
      key: '8efll2'
    }

      at stackoverflow/73035199/index.tsx:7:13

  console.log
    location:  {
      pathname: '/new-location',
      search: '',
      hash: '',
      state: undefined,
      key: 'uzhjjc'
    }

      at stackoverflow/73035199/index.tsx:7:13

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.314 s
  • Related