如何等待呈现 child 个组件

how to wait for child components rendered

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

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

//单元测试

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

render 渲染没有 child 组件。 Children 加载在例如5 秒 .. 有没有办法不用模拟 Children?我希望它们自己加载...

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

例如,如果 children 之一的元素带有 'Some string' 文本:

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

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