@@ -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 define your own custom queries as described in the example in the
151
+ [ Helpers API] ( /doc/dom-testing-library/api-helpers.md ) documentation, or via the
152
+ [ ` buildQueries ` ] ( /doc/dom-testing-library/api-helpers#buildQueries ) helper:
151
153
152
- You can define your own custom queries as described in the example in the [ Helpers API] ( api-helpers.md ) documentation.
154
+ ``` js
155
+ // custom-queries.js
156
+ import { queryHelpers , buildQueries } from ' @testing-library/react' ;
157
+
158
+ const queryAllByDataCy = (... args ) =>
159
+ queryHelpers .queryAllByAttribute (' data-cy' , ... args);
160
+
161
+ const getMultipleError = (c , dataCyValue ) => (
162
+ ` Found multiple elements with the data-cy attribute of: ${ dataCyValue} `
163
+ );
164
+ const getMissingError = (c , dataCyValue ) => (
165
+ ` Unable to find an element with the data-cy attribute of: ${ dataCyValue} `
166
+ );
167
+
168
+ const [
169
+ queryByDataCy,
170
+ getAllByDataCy,
171
+ getByDataCy,
172
+ findAllByDataCy,
173
+ findByDataCy
174
+ ] = buildQueries (
175
+ queryAllByDataCy,
176
+ getMultipleError,
177
+ getMissingError,
178
+ );
179
+
180
+ export {
181
+ queryByDataCy ,
182
+ queryAllByDataCy ,
183
+ getByDataCy ,
184
+ getAllByDataCy ,
185
+ findAllByDataCy ,
186
+ findByDataCy ,
187
+ };
188
+ ```
189
+
190
+ You can then override and append queries via the render function by passing a
191
+ [ ` queries ` ] ( api.md#render-options ) option.
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