【问题标题】:Argument of type '(content: string, node: Element | null) => boolean | null | undefined' is not assignable to parameter of type 'Matcher''(content: string, node: Element | null) => boolean | 类型的参数空 | undefined' 不可分配给“Matcher”类型的参数
【发布时间】:2021-07-23 19:47:41
【问题描述】:

我有一个 React Typescript 应用程序,在进行单元测试时,我使用下面的代码通过其 textContent 查找元素:

import { screen } from "@testing-library/react";

export function getByTextContent(textMatch: string | RegExp): HTMLElement {
  return screen.getByText((content, node) => {
    const hasText = (node: Element) =>
      node.textContent === textMatch || node.textContent?.match(textMatch);
    const nodeHasText = hasText(node as Element);
    const childrenDontHaveText = Array.from(node?.children || []).every(
      (child) => !hasText(child)
    );
    return nodeHasText && childrenDontHaveText;
  });
}

我从here获取代码

我的测试通过了,但应用程序崩溃并出现以下错误:

Argument of type '(content: string, node: Element | null) => boolean | null | undefined' is not assignable to parameter of type 'Matcher'.
  Type '(content: string, node: Element | null) => boolean | null | undefined' is not assignable to type 'MatcherFunction'.
    Type 'boolean | null | undefined' is not assignable to type 'boolean'.
      Type 'undefined' is not assignable to type 'boolean'.  TS2345

    2 | 
    3 | export function getByTextContent(textMatch: string | RegExp): HTMLElement {
  > 4 |   return screen.getByText((content, node) => {
      |                           ^
    5 |     const hasText = (node: Element) =>
    6 |       node.textContent === textMatch || node.textContent?.match(textMatch);
    7 |     const nodeHasText = hasText(node as Element);

【问题讨论】:

    标签: javascript reactjs typescript react-testing-library


    【解决方案1】:

    问题在于您使用?(如node.textContent?.match(textMatch);)结果可能是undefined,虽然它适用于javascript,但TS认为return nodeHasText && childrenDontHaveText;可能是return undefined && undefined和点指出undefined 不完全是boolean。一种方法是return nodeHasText && childrenDontHaveText || false;

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2022-08-17
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 2021-10-18
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多