how to wait for child components rendered

Viewed 754

how do I wait till child components loaded so I can check toMatchSnapshot whole Parent component?

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

//unit test

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

render renders without child components. Children are loaded in e.g. 5 sec.. Is there a way to do it without mocking Children? I want them to be loaded themself ...

1 Answers

You can use findBy* queries to wait for a certain element to be present in the DOM.

For instance, if one of the children has an element with 'Some string' text:

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

Note that findBy* queries (like waitFor) have a default 1000ms timeout, which can be increased by passing a timeout value in the options object as last parameter.

Related