Skip to content

Commit f059027

Browse files
committed
docs: add custom queries example to custom render docs
1 parent 7f53277 commit f059027

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

docs/react-testing-library/setup.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,47 @@ module.exports = {
144144

145145
</details>
146146

147+
<details>
148+
<summary>Customize queries globally with custom render</summary>
149+
150+
You can override and append queries via the render function by passing a [`queries`](api.md#render-options) option.
151+
152+
You can define your own custom queries as described in the example in the [Helpers API](api-helpers.md) documentation.
153+
154+
If you want to add custom queries globally, you can do this by defining a custom render method:
155+
156+
```js
157+
// 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+
};
166+
167+
const customRender = (ui, options) =>
168+
render(ui, { queries: { ...queries, ...customQueries } })
169+
170+
// re-export everything
171+
export * from '@testing-library/react'
172+
173+
// override render method
174+
export { customRender as render }
175+
```
176+
177+
You can then use your custom queries as you would any other query:
178+
179+
```js
180+
const { getByDataCy } = render(
181+
<Component />
182+
);
183+
184+
expect(getByDataCy('my-component')).toHaveTextContent('Hello');
185+
```
186+
</details>
187+
147188
### Configuring Jest with Test Utils
148189

149190
To make your custom test file accessible in your Jest test files without using

0 commit comments

Comments
 (0)