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

@testing-library自定义查询传可选参数触发Typescript类型错误

问题根因

@testing-library/react 提供的 buildQueries 类型定义包含多重重载逻辑,当自定义 queryAll 函数的第二个参数类型为 string | RegExp 时,TypeScript 会优先匹配内置文本查询的专用重载,该重载默认仅支持传入1个匹配参数,会直接忽略你自定义的可选 options 参数,最终导致调用时传入第二个参数报错。

解决方案

方案1:显式指定泛型参数(推荐)

直接给 buildQueries 传入你自定义的参数类型泛型,强制 TypeScript 按照你的定义匹配参数规则,不需要修改原有业务逻辑:

// 定义调用时的参数类型(排除第一个固定的container参数)
type TextContentQueryArgs = [text: string | RegExp, options?: QueryParameterOptions];

const [
  queryByTextContent,
  getAllByTextContent,
  getByTextContent,
  findAllByTextContent,
  findByTextContent
] = buildQueries<TextContentQueryArgs>(queryAllByTextContent, getMultipleError, getMissingError);

修改完成后,生成的五个查询函数会直接继承你定义的参数规则,传入第二个options参数不会再报类型错误。

方案2:参数结构封装

你也可以将匹配参数和配置项合并为单个对象参数,避开触发 string | RegExp 对应的内置重载:

// 调整queryAll函数的参数结构
const queryAllByTextContent = (
  container: HTMLElement,
  queryOpts: { text: string | RegExp, exact?: boolean }
): HTMLElement[] => {
  const { text, exact = false } = queryOpts;
  // 原有匹配逻辑保持不变
};

// 同步调整错误提示函数的参数即可
const getMultipleError = (
  container: Element | null,
  queryOpts: { text: string | RegExp }
): string => `Found multiple elements with the text: ${queryOpts.text}`;
const getMissingError = (
  container: Element | null,
  queryOpts: { text: string | RegExp }
): string => `Unable to find an element with the text: ${queryOpts.text}`;

后续调用时使用对象传参即可:getByTextContent({ text: /¥\d+\.\d{2}/, exact: false })。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:24:07