I'm trying to create a custom query for Testing Library in TypeScript? I intend to use this with a React project.
The query simply gets the first th cells in the tbody of the container:
// all-table-headings.ts - contains the custom query
import { buildQueries } from '@testing-library/dom';
const queryAllTableHeadings = (container: HTMLElement): HTMLElement[] =>
Array.from(container.querySelectorAll('thead th'));
const getMultipleError = () => '...';
const getMissingError = () => 'Could not find any table headings!';
const [
queryTableHeadings, getAllTableHeadings, getTableHeadings, findAllTableHeadings, findTableHeadings
] = buildQueries(queryAllTableHeadings, getMultipleError, getMissingError);
export {
queryTableHeadings, getAllTableHeadings, getTableHeadings, findAllTableHeadings, findTableHeadings
};
Here the query is added to a custom render function:
// index.ts - exports a custom render function
import { queries, render } from '@testing-library/react';
import * as allTableHeadings from './all-table-headings';
import * as allCellsAtRow from './all-cells-at-row';
const customRender = (ui, options = {}) =>
render(ui, {
queries: {
...queries,
...allTableHeadings,
...allCellsAtRow
},
...options
});
export * from '@testing-library/react';
export { customRender as render };
Here's a very simple usage example:
const TestComponent = () => <div>Test Component</div>;
const { getAllTableHeadings } = render(<PropsTable component={ TestComponent }/>);
const headings = getAllTableHeadings();
However TypeScript complains as follows:
TS2554: Expected 1-3 arguments, but got 0.
If I ignore the error by adding // @ts-ignore I can confirm that the custom query works, it's just TS that's a bit unhappy.
Is this something that can be fixed by adding a d.ts file, the documentation on Testing Library isn't very clear how to resolve the TypeScript approach of adding custom queries.
Here's my tsconfig.json for reference:
{
"compilerOptions": {
"esModuleInterop": true,
"jsx": "react"
}
}
