【发布时间】: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