AlbertMunichMar
AlbertMunichMar

Reputation: 1906

React testing library, how to test history.push

In a React App, I have a button that goes to a new url programatically:

<ComposeButton
  onClick={() => {
    history.push('some-link'))
  }}
>

In my test, I render my component as mentioned in the react-testing-library documentation for React Router:

const renderComponent = (page: Pages) => {
  const history = createMemoryHistory()

  return renderWithState(
    <MockedProvider
      mocks={mocks}
      addTypename={false}
      defaultOptions={{
        watchQuery: { fetchPolicy: 'no-cache' },
        query: { fetchPolicy: 'no-cache' }
      }}
    >
      <Router history={history}>
        <ComponentToRender />
      </Router>
    </MockedProvider>
  )
}

How can I wait for this change page in react-testing-library?

it('sends invitations', async () => {
    const { getByTestId, queryByTestId, debug, getByText } = renderComponent(
      Pages.contacts
    )

    await new Promise((resolve) => setTimeout(resolve))

    const writeMessageBtn = getByTestId('write-message-btn')
    waitFor(() => fireEvent.click(writeMessageBtn))
    await new Promise((resolve) => setTimeout(resolve))

    waitFor(() => debug()) // <- expect to see new page

    getByText('EV_305_NEW_INVITATION_SEND') // <- this is in the second page, never get here
})

I can never see the content of the new page (after clicking the button) when using debug

Upvotes: 3

Views: 5451

Answers (1)

thedude
thedude

Reputation: 9822

I'm not sure this will make everything work, but there are a few issues with the code sample you shared I can highlight:

  1. You are rendering a Router but no Routes. Use MemoryRouter instead and provide the same routes as your actual application - at least provide the route you are pushing into history

  2. You are not using react-testing-library correctly. Instead of using getByTestId, use findByTestId. e.g. const writeMessageBtn = await findByTestId('write-message-btn'). The difference is that get* queries are synchronous while find* are async. You don't need to wait for arbitrary timeouts, the testing library will try to find the element for a few seconds. The same applies to the other places where you use get*

Upvotes: 2

Related Questions