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

200
Vistas
Testing React Router: click event does not trigger page navigation

Background

I am testing if a page changes on a button click inside my reactjs project. Routing and changing pages are handled by react-router. There is a button that redirects the page to /my-page.

Sample code

Here is the code:

<button type="submit" onClick={() => history.push("/my-page")}>Go to my page</button>

Here is how I am trying to test this functionality:

test('should navigate to /my-page on [Go to my page] button click', () => {
    const history = createMemoryHistory()
    render(
        <MemoryRouter history={history}>
            <App />
        </MemoryRouter>, container
    )
    const myButton = screen.queryByText('Go to my page')

    // Neither of these methods actually does the clicking. 
    // myButton.dispatchEvent(new MouseEvent("click", { bubbles: true }));
    // fireEvent.click(myButton)
    userEvent.click(myButton)

    expect(history.location.pathname).toBe('/my-page')
})

Here is the error output upon running npm test:

expect(received).toBe(expected) // Object.is equality

Expected: "/my-page"
Received: "/"

Sidenotes:

  • screen.queryByText('Go to my page') does find the button required.
  • same functionality works normally when it is run on a browser

What am I missing here?

Update

It seems like running the test component by itself separate from other test components which render different pages is causing it to fail somehow. I think I might be failing to destroy previously rendered components.

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