为什么在使用findBy时测试失败,而在使用waitfor时成功?

问题描述 投票:0回答:1

使用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 )
      })
    })

但是以下测试曾经有效,但现在失败了:

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 )
    })

为什么两个代码段的功能不同?我以为findby应该是waitfor的包装器。

注意:在渲染组件的内部发生的事情是,我们调度了一个调用传奇的动作,传奇调用了fetch,它返回了一条数据,然后传奇又调用了另一个将数据作为有效载荷的动作,触发将数据保存到商店的减速器。然后,视图应更新为包括带有Copywriting.buyer.shop.popularSearch的元素。

有什么原因,原则上],为什么两个测试应该具有不同的输出?

使用react-testing-library,以下测试有效:it('提供流行的搜索词,并带有指向搜索URL的链接',()=> {waitFor(()=> {const PopularSearch = screen...。] >

reactjs testing react-redux redux-saga react-testing-library
1个回答
0
投票

这可能是因为默认超时是1000ms(https://testing-library.com/docs/dom-testing-library/api-queries#findby),而在您的第一次测试中,您手动指定了5000ms超时。

您还将在文档中注意到findBy*方法接受waitForOptions作为其第三个参数。

© www.soinside.com 2019 - 2024. All rights reserved.