@@ -147,31 +147,64 @@ module.exports = {
147
147
<details >
148
148
<summary >Customize queries globally with custom render</summary >
149
149
150
- You can override and append queries via the render function by passing a [ ` queries ` ] ( api.md#render-options ) option.
150
+ You can override and append queries via the render function by passing a
151
+ [ ` queries ` ] ( api.md#render-options ) option.
151
152
152
- You can define your own custom queries as described in the example in the [ Helpers API] ( api-helpers.md ) documentation.
153
+ You can define your own custom queries as described in the example in the
154
+ [ Helpers API] ( /doc/dom-testing-library/api-helpers.md ) documentation, or via the
155
+ [ ` buildQueries ` ] ( /doc/dom-testing-library/api-helpers#buildQueries ) helper:
156
+
157
+ ``` js
158
+ // custom-queries.js
159
+ import { queryHelpers , buildQueries } from ' @testing-library/react' ;
160
+
161
+ const queryAllByDataCy = (... args ) =>
162
+ queryHelpers .queryAllByAttribute (' data-cy' , ... args);
163
+
164
+ const getMultipleError = (c , dataCyValue ) => (
165
+ ` Found multiple elements with the data-cy attribute of: ${ dataCyValue} `
166
+ );
167
+ const getMissingError = (c , dataCyValue ) => (
168
+ ` Unable to find an element with the data-cy attribute of: ${ dataCyValue} `
169
+ );
170
+
171
+ const [
172
+ queryByDataCy,
173
+ getAllByDataCy,
174
+ getByDataCy,
175
+ findAllByDataCy,
176
+ findByDataCy
177
+ ] = buildQueries (
178
+ queryAllByDataCy,
179
+ getMultipleError,
180
+ getMissingError,
181
+ );
182
+
183
+ export {
184
+ queryByDataCy ,
185
+ queryAllByDataCy ,
186
+ getByDataCy ,
187
+ getAllByDataCy ,
188
+ findAllByDataCy ,
189
+ findByDataCy ,
190
+ };
191
+ ```
153
192
154
193
If you want to add custom queries globally, you can do this by defining a custom render method:
155
194
156
195
``` js
157
196
// test-utils.js
158
- import { render , queries , queryHelpers } from ' @testing-library/react'
159
-
160
- const customQueries = {
161
- getByDataCy: queryHelpers .queryByAttribute .bind (
162
- null ,
163
- ' data-cy'
164
- ),
165
- };
197
+ import { render , queries , queryHelpers } from ' @testing-library/react' ;
198
+ import * as customQueries from ' ./custom-queries' ;
166
199
167
200
const customRender = (ui , options ) =>
168
- render (ui, { queries: { ... queries, ... customQueries } })
201
+ render (ui, { queries: { ... queries, ... customQueries } });
169
202
170
203
// re-export everything
171
- export * from ' @testing-library/react'
204
+ export * from ' @testing-library/react' ;
172
205
173
206
// override render method
174
- export { customRender as render }
207
+ export { customRender as render };
175
208
```
176
209
177
210
You can then use your custom queries as you would any other query:
0 commit comments