Skip to content

Commit a2955c5

Browse files
authored
docs: add TypeScript example for custom-queries.js (fix #889)
1 parent 0db925f commit a2955c5

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

docs/react-testing-library/setup.mdx

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,11 @@ elements by `data-cy`, a "test ID" convention mentioned in the
155155
[Cypress.io](https://docs.cypress.io/guides/references/best-practices.html#Selecting-Elements)
156156
documentation.
157157

158+
<Tabs groupId="test-utils" defaultValue="js" values={[ {label: 'Javascript',
159+
value: 'js'}, {label: 'Typescript', value: 'ts'}, ]}>
160+
161+
<TabItem value="js">
162+
158163
```js title="custom-queries.js"
159164
import { queryHelpers, buildQueries } from '@testing-library/react'
160165

@@ -187,6 +192,54 @@ export {
187192
}
188193
```
189194

195+
</TabItem>
196+
197+
<TabItem value="ts">
198+
199+
```js title="custom-queries.ts"
200+
import {
201+
queryHelpers,
202+
buildQueries,
203+
Matcher,
204+
MatcherOptions,
205+
} from '@testing-library/react'
206+
207+
// The queryAllByAttribute is a shortcut for attribute-based matchers
208+
// You can also use document.querySelector or a combination of existing
209+
// testing library utilities to find matching nodes for your query
210+
const queryAllByDataCy = (
211+
container: HTMLElement,
212+
id: Matcher,
213+
options?: MatcherOptions | undefined
214+
) => queryHelpers.queryAllByAttribute('data-cy', container, id, options)
215+
216+
const getMultipleError = (c, dataCyValue) =>
217+
`Found multiple elements with the data-cy attribute of: ${dataCyValue}`
218+
const getMissingError = (c, dataCyValue) =>
219+
`Unable to find an element with the data-cy attribute of: ${dataCyValue}`
220+
221+
const [
222+
queryByDataCy,
223+
getAllByDataCy,
224+
getByDataCy,
225+
findAllByDataCy,
226+
findByDataCy,
227+
] = buildQueries(queryAllByDataCy, getMultipleError, getMissingError)
228+
229+
export {
230+
queryByDataCy,
231+
queryAllByDataCy,
232+
getByDataCy,
233+
getAllByDataCy,
234+
findAllByDataCy,
235+
findByDataCy,
236+
}
237+
```
238+
239+
</TabItem>
240+
241+
</Tabs>
242+
190243
You can then override and append the new queries via the render function by
191244
passing a [`queries`](api.mdx#render-options) option.
192245

0 commit comments

Comments
 (0)