In a current project using react with jest and @testing-library/react, I'm implementing custom queries to query the text content of components.
The custom query (built with testing-library's buildQueries method) I want to use receives two parameters (one is optional). When I want to add a second parameter, Typescript tells me that only one argument can be passed.
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);
I have created a Github repository with a working example:
https://github.com/desudo/example-jest-with-react-testing-library
Most important files are:
/test/helpers/textContentQueries.ts -> queryAllByTextContent
/test/component/Price.test.tsx
What I found out:
The first parameter of the custom query has to be of type string | RegExp.
When I set the type to just a string, everything works as intended.
IMPORTANT
The example tests are just dummy tests to show the Typescript error.
Thank you for any hint or solution!
One way of fixing this issue is to add the parameter options?: QueryParameterOptions to both getMultipleError and getMissingError.
This is due to the type that is being defined under the hood of buildQueries.
I certainly do not like this solution because we are not using the options parameter in either of these two methods.