【发布时间】:2021-12-27 15:45:00
【问题描述】:
在使用react 和jest 和@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