Skip to content

Commit b582bd7

Browse files
authored
feat(render): options.wrapper api + customRender usage (#39)
- Adds docs for render option "wrapper": testing-library/react-testing-library#303 - Reorganizes the API and Setup pages for rtl slightly to add better heading structure for the right navbar. Accidentally got remotes mixed up - this reverts the revert that prematurely merged the change. This reverts commit c47aae0.
1 parent c47aae0 commit b582bd7

File tree

2 files changed

+101
-86
lines changed

2 files changed

+101
-86
lines changed

docs/react-testing-library/api.md

+33-16
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ title: API
66
`react-testing-library` re-exports everything from `dom-testing-library` as well
77
as these methods:
88

9+
- [`render`](#act)
10+
- [`cleanup`](#cleanup)
11+
- [`act`](#act)
12+
13+
---
14+
915
## `render`
1016

1117
```typescript
@@ -44,19 +50,17 @@ test('renders a message', () => {
4450
> The [cleanup](#cleanup) function should be called between tests to remove the
4551
> created DOM nodes and keep the tests isolated.
4652

47-
### `render` Options
48-
49-
<details>
50-
51-
<summary>Expand to see documentation on the options</summary>
53+
## `render` Options
5254

5355
You wont often need to specify options, but if you ever do, here are the
5456
available options which you could provide as a second argument to `render`.
5557

56-
**container**: By default, `react-testing-library` will create a `div` and
57-
append that div to the `document.body` and this is where your react component
58-
will be rendered. If you provide your own HTMLElement `container` via this
59-
option, it will not be appended to the `document.body` automatically.
58+
### `container`
59+
60+
By default, `react-testing-library` will create a `div` and append that div to
61+
the `document.body` and this is where your react component will be rendered. If
62+
you provide your own HTMLElement `container` via this option, it will not be
63+
appended to the `document.body` automatically.
6064

6165
For Example: If you are unit testing a `tablebody` element, it cannot be a child
6266
of a `div`. In this case, you can specify a `table` as the render `container`.
@@ -69,26 +73,35 @@ const { container } = render(<TableBody {...props} />, {
6973
})
7074
```
7175

72-
**baseElement**: If the `container` is specified, then this defaults to that,
73-
otherwise this defaults to `document.documentElement`. This is used as the base
74-
element for the queries as well as what is printed when you use `debug()`.
76+
### `baseElement`
77+
78+
If the `container` is specified, then this defaults to that, otherwise this
79+
defaults to `document.documentElement`. This is used as the base element for the
80+
queries as well as what is printed when you use `debug()`.
81+
82+
### `hydrate`
7583

76-
**hydrate**: If hydrate is set to true, then it will render with
84+
If hydrate is set to true, then it will render with
7785
[ReactDOM.hydrate](https://reactjs.org/docs/react-dom.html#hydrate). This may be
7886
useful if you are using server-side rendering and use ReactDOM.hydrate to mount
7987
your components.
8088

81-
</details>
89+
### `wrapper`
8290

83-
---
91+
Pass a React Component as the `wrapper` option to have it rendered around the
92+
inner element. This is most useful for creating reusable custom render functions
93+
for common data providers. See [setup](setup.md#custom-render) for examples.
94+
95+
## `render` Result
8496

8597
The `render` method returns an object that has a few properties:
8698

8799
### `...queries`
88100

89101
The most important feature of `render` is that the queries from
90102
[dom-testing-library](api-queries.md) are automatically returned with their
91-
first argument bound to the rendered container.
103+
first argument bound to the [baseElement](#baseelement), which defaults to
104+
`document.body`.
92105

93106
See [Queries](api-queries.md) for a complete list.
94107

@@ -222,6 +235,8 @@ fireEvent.click(getByText(/Click to increase/))
222235
expect(firstRender).toMatchDiffSnapshot(asFragment())
223236
```
224237
238+
---
239+
225240
## `cleanup`
226241
227242
Unmounts React trees that were mounted with [render](#render).
@@ -248,6 +263,8 @@ that you configure your test framework to run a file before your tests which
248263
does this automatically. See the [setup](./setup) section for guidance on how to
249264
set up your framework.
250265
266+
---
267+
251268
## `act`
252269
253270
This is a light wrapper around the

docs/react-testing-library/setup.md

+68-70
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,22 @@ sidebar_label: Setup
88
demonstrated in the example above). However, there are some things you can do
99
when configuring your testing framework to reduce some boilerplate. In these
1010
docs we'll demonstrate configuring Jest, but you should be able to do similar
11-
things with any testing framework (react-testing-library does not require that
12-
you use Jest).
11+
things with [any testing framework](#using-without-jest) (react-testing-library
12+
does not require that you use Jest).
1313

1414
## Global Config
1515

16-
There are several options you can add to your global test config that simplify
17-
the setup and teardown of tests in individual files. For example, you can ensure
18-
[`cleanup`](./api#cleanup) is called after each test and import additional
19-
assertions.
16+
Adding options to your global test config can simplify the setup and teardown of
17+
tests in individual files.
2018

21-
To do this with Jest 24 and up, you can add the
19+
### Cleanup
20+
21+
You can ensure [`cleanup`](./api#cleanup) is called after each test and import
22+
additional assertions by adding it to the setup configuration in Jest.
23+
24+
In Jest 24 and up, add the
2225
[`setupFilesAfterEnv`](https://jestjs.io/docs/en/configuration.html#setupfilesafterenv-array)
23-
option to your Jest config.
26+
option to your Jest config:
2427

2528
```javascript
2629
// jest.config.js
@@ -33,10 +36,10 @@ module.exports = {
3336
}
3437
```
3538

36-
### Older versions of Jest
37-
3839
<details>
3940

41+
<summary>Older versions of Jest</summary>
42+
4043
Jest versions 23 and below use the
4144
[`setupTestFrameworkScriptFile`](https://jestjs.io/docs/en/23.x/configuration#setuptestframeworkscriptfile-string)
4245
option in your Jest config instead of `setupFilesAfterEnv`. This setup file can
@@ -72,7 +75,11 @@ It's often useful to define a custom render method that includes things like
7275
global context providers, data stores, etc. To make this available globally, one
7376
approach is to define a utility file that re-exports everything from
7477
`react-testing-library`. You can replace react-testing-library with this file in
75-
all your imports.
78+
all your imports. See [below](#comfiguring-jest-with-test-utils) for a way to
79+
make your test util file accessible without using relative paths.
80+
81+
The example below sets up data providers using the
82+
[`wrapper`](api.md#render-options) option to `render`.
7683

7784
```diff
7885
// my-component.test.js
@@ -87,27 +94,64 @@ import { ThemeProvider } from 'my-ui-lib'
8794
import { TranslationProvider } from 'my-i18n-lib'
8895
import defaultStrings from 'i18n/en-x-default'
8996

90-
const customRender = (node, options) => {
91-
return render(
97+
const AllTheProviders = ({ children }) => {
98+
return (
9299
<ThemeProvider theme="light">
93100
<TranslationProvider messages={defaultStrings}>
94-
{node}
101+
{children}
95102
</TranslationProvider>
96-
</ThemeProvider>,
97-
options
103+
</ThemeProvider>
98104
)
99105
}
100106

107+
const customRender = (ui, options) =>
108+
render(ui, { wrapper: AllTheProviders, ...options })
109+
101110
// re-export everything
102111
export * from 'react-testing-library'
103112

104113
// override render method
105114
export { customRender as render }
106115
```
107116

108-
To make this file accessible without using relative imports, add the folder
109-
containing the file to the Jest `moduleDirectories` option. Note: this will make
110-
_all_ the .js files in that directory importable without `../`.
117+
> **Note**
118+
>
119+
> Babel versions lower than 7 throw an error when trying to override the named
120+
> export in the example above. See
121+
> [#169](https://github.com/kentcdodds/react-testing-library/issues/169) and the
122+
> workaround below.
123+
124+
<details>
125+
<summary>Workaround for Babel 6</summary>
126+
127+
You can use CommonJS modules instead of ES modules, which should work in Node:
128+
129+
```js
130+
// test-utils.js
131+
const rtl = require('react-testing-library')
132+
133+
const customRender = (ui, options) =>
134+
rtl.render(ui, {
135+
myDefaultOption: 'something',
136+
...options,
137+
})
138+
139+
module.exports = {
140+
...rtl,
141+
render: customRender,
142+
}
143+
```
144+
145+
</details>
146+
147+
### Configuring Jest with Test Utils
148+
149+
To make your custom test file accessible in your Jest test files without using
150+
relative imports (`../../test-utils`), add the folder containing the file to the
151+
Jest `moduleDirectories` option.
152+
153+
This will make all the `.js` files in the test-utils directory importable
154+
without `../`.
111155

112156
```diff
113157
// my-component.test.js
@@ -128,9 +172,11 @@ module.exports = {
128172
}
129173
```
130174

131-
If your project is based on top of Create React App, to make the file accessible
132-
without using relative imports, you just need to create a `.env` file in the
133-
root of your project with the following configuration:
175+
### Jest and Create React App
176+
177+
If your project is based on top of Create React App, to make the `test-utils`
178+
file accessible without using relative imports, you just need to create a `.env`
179+
file in the root of your project with the following configuration:
134180

135181
```
136182
// Create React App project structure
@@ -151,54 +197,6 @@ $ app
151197
NODE_PATH=src/utils
152198
```
153199

154-
There is the case when you want to wrap your components in a `Provider`, this
155-
might cause conflicts when `rerender`ed. To achieve this, we suggest the
156-
`rerender` should be implemented the same way custom queries, by changing the
157-
return value of the customRender.
158-
159-
```js
160-
// test-utils.js
161-
162-
const customRender = (ui, options) => {
163-
const rendered = render(<div>{ui}</div>, options)
164-
return {
165-
...rendered,
166-
rerender: newUi =>
167-
customRender(newUi, {
168-
container: rendered.container,
169-
baseElement: rendered.baseElement,
170-
}),
171-
}
172-
}
173-
```
174-
175-
### Export Issue with Babel Versions Lower Than 7
176-
177-
Babel versions lower than 7 throw an error when trying to override the named
178-
export in the example above. (See
179-
[#169](https://github.com/kentcdodds/react-testing-library/issues/169).)
180-
181-
<details>
182-
<summary>Workaround</summary>
183-
184-
You can use CommonJS modules instead of ES modules, which should work in Node:
185-
186-
```js
187-
// test-utils.js
188-
const rtl = require('react-testing-library')
189-
190-
const customRender = (node, options) => {
191-
return rtl.render(<Something>{node}</Something>)
192-
}
193-
194-
module.exports = {
195-
...rtl,
196-
render: customRender,
197-
}
198-
```
199-
200-
</details>
201-
202200
## Using without Jest
203201

204202
If you're running your tests in the browser bundled with webpack (or similar)

0 commit comments

Comments
 (0)