首页 > 解决方案 > '(content: string, node: Element | null) => boolean | 类型的参数 空 | undefined' 不可分配给“Matcher”类型的参数

问题描述

我有一个 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;
  });
}

我从这里拿了代码

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

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);

标签: javascriptreactjstypescriptreact-testing-library

解决方案


问题是当您使用?(如node.textContent?.match(textMatch);)结果可能是undefined,虽然它对 javascript 很好,但 TS 认为这return nodeHasText && childrenDontHaveText;可能是return undefined && undefined并指出这undefined不是boolean。一种方法是return nodeHasText && childrenDontHaveText || false;


推荐阅读