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

164
Vistas
jest testing mock history.push not called even though it was called in the component

I have a component called componentA that render some text and a button like this:

// Do some import statements
// ComponentA
function ComponentA() {
  const [submitState, setState] = useState(false);
  useEffect(()=> {
   if (submitState) {
     console.log("history.push called");
     history.push('/new-route');
   }
  }) 

  return ( <div>Hello 
  <Button onClick ={()=> setState(true}> Click here </Button>  
  </div>);
}

I want to test that upon clicking the button, history.push is called with the argument /new-route. Here is my testing:

import {render} from '@testing-library/react'

describe("Test Component A", () => {
  const history = createMemoryHistory();
  const pushSpy = jest.spyOn(history, 'push');

  test("it should call history.push with correct argument", async () => {
     //render componentA
      const {container} = render(<ComponentA  />)
     // Point B: click
     fireEvent.click(screen.getByText('Click here'));
     // Poin C: assert that the history.push is called
      expect(pushSpy).toHaveBeenCalledWith('/new-route');
  });
});

I expected this to pass because the line where the history.push did print out that it was called which meant history.push did run. And when I printed out history.location.pathname it also returned the correct route. However the test still failed with the message:

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

Number of calls: 0

Anyone knows why ? Thank you

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