0
# Test Renderer Creation
1
2
Core functionality for creating test renderer instances and managing their lifecycle. This is the primary entry point for all react-test-renderer functionality.
3
4
## Capabilities
5
6
### Create Function
7
8
Creates a test renderer instance for a React element.
9
10
```javascript { .api }
11
/**
12
* Creates a test renderer instance for a React element
13
* @param element - React element to render
14
* @param options - Optional configuration for rendering behavior
15
* @returns TestRenderer instance with methods for inspection and manipulation
16
*/
17
function create(
18
element: React.ReactElement<any>,
19
options?: TestRendererOptions
20
): TestRenderer;
21
22
interface TestRendererOptions {
23
/** Function to create mock DOM nodes for host components */
24
createNodeMock?: (element: React.ReactElement<any>) => any;
25
/** Enable concurrent rendering features (deprecated option) */
26
unstable_isConcurrent?: boolean;
27
/** Enable strict mode for additional checks */
28
unstable_strictMode?: boolean;
29
}
30
```
31
32
**Usage Examples:**
33
34
```javascript
35
import React from 'react';
36
import { create } from 'react-test-renderer';
37
38
// Basic usage
39
const component = create(<button>Click me</button>);
40
41
// With options
42
const componentWithMocks = create(
43
<input type="text" />,
44
{
45
createNodeMock: (element) => {
46
if (element.type === 'input') {
47
return {
48
focus: jest.fn(),
49
blur: jest.fn()
50
};
51
}
52
return null;
53
}
54
}
55
);
56
57
// With strict mode
58
const strictComponent = create(
59
<MyComponent />,
60
{ unstable_strictMode: true }
61
);
62
```
63
64
### TestRenderer Instance
65
66
The object returned by `create()` with methods for interacting with the rendered tree.
67
68
```javascript { .api }
69
interface TestRenderer {
70
/** Converts the rendered tree to a JSON representation for snapshot testing */
71
toJSON(): ReactTestRendererNode | Array<ReactTestRendererNode> | null;
72
/** Returns the internal tree representation (for advanced usage) */
73
toTree(): any;
74
/** Re-renders the tree with a new element */
75
update(element: React.ReactElement<any>): void;
76
/** Unmounts the rendered tree and cleans up resources */
77
unmount(): void;
78
/** Gets the root component instance */
79
getInstance(): React.Component<any, any> | any | null;
80
/** Root test instance for tree traversal and searching */
81
readonly root: ReactTestInstance;
82
/** Synchronously flush any pending updates */
83
unstable_flushSync: (fn: () => void) => void;
84
}
85
```
86
87
### toJSON Method
88
89
Serializes the rendered tree to a JSON representation suitable for snapshot testing.
90
91
```javascript { .api }
92
/**
93
* Converts the rendered tree to a JSON representation
94
* @returns JSON object, array of objects, or null for empty trees
95
*/
96
toJSON(): ReactTestRendererNode | Array<ReactTestRendererNode> | null;
97
```
98
99
**Usage Examples:**
100
101
```javascript
102
const component = create(
103
<div className="container">
104
<span>Hello</span>
105
<span>World</span>
106
</div>
107
);
108
109
const json = component.toJSON();
110
console.log(json);
111
// {
112
// type: 'div',
113
// props: { className: 'container' },
114
// children: [
115
// { type: 'span', props: {}, children: ['Hello'] },
116
// { type: 'span', props: {}, children: ['World'] }
117
// ]
118
// }
119
120
// Empty component returns null
121
const empty = create(null);
122
console.log(empty.toJSON()); // null
123
124
// Multiple root elements return array
125
const multiple = create([<div key="1">First</div>, <div key="2">Second</div>]);
126
console.log(multiple.toJSON()); // Array of two objects
127
```
128
129
### toTree Method
130
131
Returns the internal tree representation (mainly for advanced debugging).
132
133
```javascript { .api }
134
/**
135
* Returns the internal tree representation
136
* @returns Internal tree structure (implementation details may change)
137
*/
138
toTree(): any;
139
```
140
141
### update Method
142
143
Re-renders the tree with a new element, useful for testing component updates.
144
145
```javascript { .api }
146
/**
147
* Re-renders the tree with a new element
148
* @param element - New React element to render
149
*/
150
update(element: React.ReactElement<any>): void;
151
```
152
153
**Usage Examples:**
154
155
```javascript
156
const component = create(<Counter count={0} />);
157
158
// Update with new props
159
component.update(<Counter count={5} />);
160
161
// Verify the update
162
expect(component.toJSON()).toMatchSnapshot();
163
```
164
165
### unmount Method
166
167
Unmounts the rendered tree and cleans up resources.
168
169
```javascript { .api }
170
/**
171
* Unmounts the rendered tree and cleans up resources
172
*/
173
unmount(): void;
174
```
175
176
### getInstance Method
177
178
Gets the root component instance for class components.
179
180
```javascript { .api }
181
/**
182
* Gets the root component instance
183
* @returns Component instance for class components, null for function components
184
*/
185
getInstance(): React.Component<any, any> | any | null;
186
```
187
188
**Usage Examples:**
189
190
```javascript
191
class MyComponent extends React.Component {
192
myMethod() {
193
return 'test';
194
}
195
196
render() {
197
return <div>Component</div>;
198
}
199
}
200
201
const component = create(<MyComponent />);
202
const instance = component.getInstance();
203
console.log(instance.myMethod()); // 'test'
204
205
// Function components return null
206
const funcComponent = create(<div>Function component</div>);
207
console.log(funcComponent.getInstance()); // null
208
```
209
210
### unstable_flushSync Method
211
212
Synchronously flushes any pending updates (for advanced testing scenarios).
213
214
```javascript { .api }
215
/**
216
* Synchronously flush any pending updates
217
* @param fn - Function to execute before flushing
218
*/
219
unstable_flushSync: (fn: () => void) => void;
220
```
221
222
## Utility Functions
223
224
### act Function
225
226
Utility function for wrapping code that triggers React updates, ensuring proper batching and timing.
227
228
```javascript { .api }
229
/**
230
* Wraps code that triggers React updates for proper testing
231
* @param callback - Function that triggers updates
232
* @returns Promise that resolves when updates complete
233
*/
234
function act(callback: () => void | Promise<void>): Promise<void>;
235
```
236
237
**Usage Examples:**
238
239
```javascript
240
import { create, act } from 'react-test-renderer';
241
242
let component;
243
await act(async () => {
244
component = create(<AsyncComponent />);
245
});
246
247
// Make assertions after act completes
248
expect(component.toJSON()).toMatchSnapshot();
249
250
// For updates
251
await act(async () => {
252
component.update(<AsyncComponent newProp="value" />);
253
});
254
```
255
256
### unstable_batchedUpdates Function
257
258
Batches multiple updates together for performance.
259
260
```javascript { .api }
261
/**
262
* Batches multiple updates together
263
* @param callback - Function that performs updates
264
* @returns Return value of the callback
265
*/
266
function unstable_batchedUpdates<T>(callback: () => T): T;
267
```
268
269
## Constants
270
271
### version
272
273
React version string.
274
275
```javascript { .api }
276
/**
277
* React version string
278
*/
279
const version: string;
280
```
281
282
### _Scheduler
283
284
Internal scheduler object (for React team usage, not recommended for public use).
285
286
```javascript { .api }
287
/**
288
* Internal scheduler object (unstable, for React team usage)
289
*/
290
const _Scheduler: any;
291
```