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.