【问题标题】:how to wait for child components rendered如何等待子组件渲染
【发布时间】:2021-05-02 15:59:18
【问题描述】:

如何等到子组件加载后才能检查 toMatchSnapshot 整个父组件?

<MyComponent>
    <Child1 />
    <Child2 />
</MyComponent>

//单元测试

it('test parent component', () => {
    let mycomponent = render(<MyComponent />)
    expect(mycomponent.asFragment()).toMatchSnapshot()
})

渲染没有子组件。孩子们被装载在例如5 秒.. 有没有办法在不嘲笑孩子的情况下做到这一点?我希望它们自己加载...

【问题讨论】:

    标签: reactjs unit-testing react-testing-library


    【解决方案1】:

    您可以使用findBy* queries 等待某个元素出现在 DOM 中。

    例如,如果其中一个孩子有一个带有'Some string' 文本的元素:

    it('test parent component', async () => {
        let mycomponent = render(<MyComponent />)
        await screen.findByText('Some string')
        expect(mycomponent.asFragment()).toMatchSnapshot()
    })
    

    请注意,findBy* 查询(如 waitFor)有一个默认的 1000 毫秒超时,可以通过在 options 对象中传递一个 timeout 值作为最后一个参数来增加。

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 2022-12-11
      • 2019-12-29
      • 2022-12-03
      • 2023-04-01
      • 1970-01-01
      • 2020-08-19
      • 2016-09-15
      • 2017-01-14
      相关资源
      最近更新 更多