gpt4 book ai didi

reactjs - React测试库,如何测试history.push

转载 作者:行者123 更新时间:2023-12-04 15:13:34 25 4
gpt4 key购买 nike

在 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时,我永远看不到新页面的内容(点击按钮后)

最佳答案

我不确定这会让一切正常,但我可以强调您共享的代码示例存在一些问题:

  1. 您正在渲染一个 Router 但没有 Routes。使用 MemoryRouter相反,并提供与您的实际应用程序相同的路线 - 至少提供您插入历史的路线

  2. 您没有正确使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com