Dav*_*aun 6 testing reactjs redux-saga react-redux react-testing-library
使用 react-testing-library,以下测试有效:
it( 'renders popular search terms, with links to search urls', () => {
waitFor(() => {
const popularSearch = screen.getByText( Copywriting.buyer.shop.popularSearch, {}, { timeout: 5000 })
expect( popularSearch ).toBeInTheDocument()
const popularSearchPills = screen.findAllByTestId( 'pill' )
expect( popularSearchPills.length ).toBeGreaterThan( 0 )
const hrefs = popularSearchPills.map( pill => pill.href )
expect( hrefs.filter( urlIsValidAndNotBaseUrl )).not.toHaveLength( 0 )
})
})
Run Code Online (Sandbox Code Playgroud)
但是以下测试曾经有效,但现在失败了:
it( 'renders popular search terms, with links to search urls', async () => {
const popularSearch = await screen.findByText( Copywriting.buyer.shop.popularSearch )
expect( popularSearch ).toBeInTheDocument()
const popularSearchPills = await screen.findAllByTestId( 'pill' )
expect( popularSearchPills.length ).toBeGreaterThan( 0 )
const hrefs = popularSearchPills.map( pill => pill.href )
expect( hrefs.filter( urlIsValidAndNotBaseUrl )).not.toHaveLength( 0 )
})
Run Code Online (Sandbox Code Playgroud)
为什么这两个代码片段的功能不同?我认为 findby 应该是 waitfor 的包装器。
注意:渲染组件的幕后发生的事情是我们调度一个调用 saga 的动作,saga 调用fetch,它返回一个数据,然后 saga 调用另一个以数据作为有效载荷的动作,触发一个 reducer将数据保存到商店。然后视图应该更新以包含带有 的元素Copywriting.buyer.shop.popularSearch。
原则上,为什么这两个测试应该有不同的输出,有什么理由吗?
Gab*_*oli 10
这可能是因为默认超时为 1000 毫秒(https://testing-library.com/docs/dom-testing-library/api-queries#findby),而在第一个测试中,您手动指定了 5000 毫秒超时。
您还会在文档中注意到这些findBy*方法接受waitForOptions作为第三个参数。
所以你应该
const popularSearch = await screen.findByText(Copywriting.buyer.shop.popularSearch, undefined, {
timeout: 5000
});
Run Code Online (Sandbox Code Playgroud)
现在这两个测试将是相同的。
| 归档时间: |
|
| 查看次数: |
1876 次 |
| 最近记录: |