javascript - '(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);
解决方案
问题是当您使用?
(如node.textContent?.match(textMatch);
)结果可能是undefined
,虽然它对 javascript 很好,但 TS 认为这return nodeHasText && childrenDontHaveText;
可能是return undefined && undefined
并指出这undefined
不是boolean
。一种方法是return nodeHasText && childrenDontHaveText || false;
推荐阅读
- ios - 带有 isHidden 的视图总是在视图控制器启动时出现
- python - 搜索后的熊猫设置值?
- reactjs - Reactjs中表格组件行之间的间距
- python - 为什么 django rest 序列化程序中的 random 总是返回相同的字段?
- c++ - 使用 Cmake 链接休息床
- ssl - Keycloak 证书认证
- grafana - Grafana 仪表板自定义变量作为 json 对象
- sql-server - 使用 string_id 而不是可连接的连接 2 个表
- docker - 如何通过 docker swarm 将容器与同一节点上的另一个容器连接起来
- python - 下载 tar 文件但从 requests 库中的 requests.get() 函数获取 HTML 代码