【问题标题】:Testing-library custom query Typescript error测试库自定义查询打字稿错误
【发布时间】:2021-12-27 15:45:00
【问题描述】:

在使用reactjest@testing-library/react 的当前项目中,我正在实施自定义查询来查询组件的文本内容

我想使用的自定义查询(使用测试库的buildQueries 方法构建)接收两个参数(一个是可选的)。当我想添加第二个参数时,Typescript 告诉我只能传递一个参数。

const queryAllByTextContent = (
  container: HTMLElement,
  text: string | RegExp,
  options?: QueryParameterOptions
): HTMLElement[] => {
  const { exact = false } = options ?? { };

  return queryAllByText(container, (content, node): boolean => {
    if (!node) {
      return false;
    }
    const nodeHasSearchText = nodeContainsSearchText({ searchText: text, exact, node });
    // eslint-disable-next-line unicorn/prefer-spread
    const childNodesDontHaveSearchText = Array.from(node.children).every(
      (childNode): boolean => !nodeContainsSearchText({ searchText: text, exact, node: childNode })
    );

    return nodeHasSearchText && childNodesDontHaveSearchText;
  });
};

const getMultipleError = (
  container: Element | null,
  text: string | RegExp
): string => `Found multiple elements with the text: ${text}`;
const getMissingError = (
  container: Element | null,
  text: string | RegExp
): string => `Unable to find an element with the text: ${text}`;

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

我创建了一个带有工作示例的 Github 存储库:

https://github.com/desudo/example-jest-with-react-testing-library

最重要的文件是:

/test/helpers/textContentQueries.ts -> queryAllByTextContent /test/component/Price.test.tsx

我发现了什么

自定义查询的第一个参数必须是类型为string | RegExp。 当我将类型设置为 just 一个字符串时,一切都按预期工作。

重要

示例测试只是显示 Typescript 错误的虚拟测试。


感谢您的任何提示或解决方案!

【问题讨论】:

  • 我不确定这是您的自定义查询。相反,我认为这是您对queryAllBy 的使用。您将两个参数传递给queryAllByText(),而在 React 测试库中它只需要一个参数(加上选项对象)。这条语句:“而不是 getByText(node, 'text') you do getByText('text')”可以在here找到。
  • 这不是指getByText 用于测试用例吗?在使用buildQueries 方法构建和导出查询之前使用queryAllByText。 TypeScript Intellisense 还建议queryAllByText 可以接收(container: HTMLElement, id: Matcher, options: SelectorMatcherOptions)
  • @juliomalves 感谢您提供的信息。我会相应地添加代码sn-ps。

标签: javascript reactjs typescript jestjs react-testing-library


【解决方案1】:

解决此问题的一种方法是将参数options?: QueryParameterOptions 添加到getMultipleErrorgetMissingError

这是由于在 buildQueries 的底层定义的类型。

我当然不喜欢这个解决方案,因为我们没有在这两种方法中使用 options 参数。

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 2019-07-30
    • 2017-12-22
    • 2018-08-24
    • 2022-01-11
    • 2018-04-20
    • 1970-01-01
    • 2017-09-09
    • 2018-01-05
    相关资源
    最近更新 更多