Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

86
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda