如何等待子组件加载完毕,以便检查 toMatchSnapshot 整个父组件?
<MyComponent>
<Child1 />
<Child2 />
</MyComponent>
//单元测试
it('test parent component', () => {
let mycomponent = render(<MyComponent />)
expect(mycomponent.asFragment()).toMatchSnapshot()
})
render 渲染没有子组件。儿童装载在例如5 秒.. 有没有办法不嘲笑孩子呢?我希望它们自己加载...
答案 0 :(得分: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 毫秒,可以通过在 timeout
对象中将 options
值作为最后一个参数传递来增加该超时时间。