3

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.

Beki
  • 1,344
  • 1
  • 12
  • 22
  • can u open a codesandbox and share link. – Siful Islam Aug 06 '21 at 06:01
  • A suggestion for testing: try to test your logic, don't make a test to verify if a particular libray does his job. Starting from the fact that I think people that wrote that library already test it, for you will be just a waste of time. In your case, is 100% sure that history will push `'/my-page'` into `history.location.pathname`. Try instead to test if there are some reasons why the button could be disabled or not visible (wrong boolean condition??). Making a test like this, according to my personal point of view, is like test `expect(1+1).toBe(2)`. – Giovanni Esposito Aug 06 '21 at 07:09
  • 2
    @GiovanniEsposito I wish I could explain that to a Japanese client. They insist to see the test done on page navigation. – Beki Aug 06 '21 at 07:38

0 Answers0