在 React 应用程序中,我有一个以编程方式转到新 url 的按钮:
<ComposeButton
onClick={() => {
history.push('some-link'))
}}
>
在我的测试中,我按照 React Router 的 react-testing-library 文档中提到的方式渲染我的组件。 :
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>
)
}
我如何在 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
})
使用debug
时,我永远看不到新页面的内容(点击按钮后)
最佳答案
我不确定这会让一切正常,但我可以强调您共享的代码示例存在一些问题:
您正在渲染一个
Router
但没有Routes
。使用 MemoryRouter相反,并提供与您的实际应用程序相同的路线 - 至少提供您插入历史的路线您没有正确使用
的其他地方react-testing-library
。不要使用getByTestId
,而是使用findByTestId
。例如const writeMessageBtn = await findByTestId('write-message-btn')
。不同之处在于get*
查询是同步的,而find*
是异步的。您不需要等待任意超时,测试库将尝试在几秒钟内找到该元素。 这同样适用于您使用get*
关于reactjs - React测试库,如何测试history.push,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64737750/