Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

85
Views
Test router inside useEffect hook

I have the following component.
Looking to test that the router method push within useEffect is being called with a certain path and search.

import React from 'react';
import { compose } from 'redux';
import { withRouter } from 'react-router';

const MyComponent = ({
  router: { push, location },
}) => {
    const version = 'v2';
  React.useEffect(() => {
    push({
      pathname: `/${version}/new_path`,
      search: location.search ? location.search: '',
    });
  }, []);
  return <div>Sample div text</div>
};

const higherOrder = compose(
  withRouter,
  aCustomHigherOrderC,
);

export default higherOrder(MyComponent);

This is the test I have written to test that the router is being called correctly.

import React from 'react';
import { shallow } from 'enzyme';
import MyComponent from '../src/components/MyComponent';

jest.spyOn(React, 'useEffect').mockImplementation(f => f());

const props = {
  router: {
    push: jest.fn(),
    location: {
      search: '?param=1',
    },
  },
};

describe('MyComponent component tests', () => {
  it('should work', () => {
    const render = () => shallow(
      <MyComponent {...props} />
    );
    expect(props.router.push).toHaveBeenCalledWith('/v2/new_path?param=1');
  });
});

But I get the following error when I run the test.

Error: expect(jest.fn()).toHaveBeenCalledWith(expected)

Expected mock function to have been called with: ["/v2/new_path?param=1"] But it was not called.

It seems like I did not even enter useEffect. Did try to add a break point in there and I do not hit that break point. Could I please get some advice on what I am doing wrong and how I could test the router that it is being called with correct path and search param? Thanks.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!