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

TypeScript中Testing Library的within返回类型适配问题

替换Testing Library辅助函数中的any类型方案

注:within是getQueriesForElement的别名,其定义可查看Testing Library类型源码中get-queries-for-element.d.ts文件的第178-182行内容。

解决步骤

  • 导入所需类型:从@testing-library/react(或@testing-library/dom)中导入对应类型,这些类型对应Testing Library的查询方法集合:
import { Screen, BoundFunctions, Queries } from '@testing-library/react';
  • 修改辅助函数类型:将container参数的any替换为BoundFunctions<Queries>,这就是within方法返回对象的正确类型,最终函数定义如下:
const getSomething = (name: string, container: Screen | BoundFunctions<Queries> = screen) => {
  return container.getByRole('someRole', { name });
};

类型说明

  • BoundFunctions<Queries>:代表绑定到指定元素容器上的查询方法集合,正是within调用后的返回类型,包含getByRole等所有Testing Library查询方法。
  • Screen类型本身继承了BoundFunctions<Queries>,因此这个联合类型可以同时兼容全局screen对象和within返回的容器对象,完全覆盖你的使用场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 12:22:10