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

197
Views
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
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!