Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda