You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Testing Library如何实现等待多个元素全部被移除?

解决方案

React Testing Library 官方的 waitForElementToBeRemoved 本身就支持等待多个元素移除,不需要额外实现自定义方法,有两种常见实现方式:

推荐方案:传入查询回调函数

直接给 waitForElementToBeRemoved 传入返回骨架屏元素列表的查询函数,这是最稳妥的实现方式,不会出现提前抓取元素后组件重渲染导致的引用失效问题:

test("SomeComponent when loaded doesn't render any skeleton", async () => {
  render(<SomeComponent />)

  // 内部会自动轮询,直到所有匹配testId为skeleton的元素全部被移除
  await waitForElementToBeRemoved(() => screen.getAllByTestId("skeleton"));

  expect(screen.queryByTestId("skeleton")).not.toBeInTheDocument();
});

该方案和你需要的waitForMultipleElementsToBeRemoved效果完全一致,会自动处理重试、超时逻辑,只要所有匹配元素全部移除后才会结束等待。

兼容旧版本方案:结合 Promise.all 批量处理

如果你使用的是非常老的 React Testing Library 版本,不支持传入回调函数或元素数组,可以用Promise.all批量等待每个元素移除:

test("SomeComponent when loaded doesn't render any skeleton", async () => {
  render(<SomeComponent />)

  const skeletons = screen.getAllByTestId("skeleton");
  await Promise.all(skeletons.map(item => waitForElementToBeRemoved(item)));

  expect(screen.queryByTestId("skeleton")).not.toBeInTheDocument();
});

注意该方案存在限制:如果等待过程中原有骨架屏元素被卸载后,又渲染了新的同testId骨架屏元素,该逻辑会出现漏判,因此非必要不推荐使用。

内容的提问来源于stack exchange,提问作者DLO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:48:02