0
# Configuration
1
2
Configure React Testing Library behavior globally or per-test.
3
4
## API
5
6
```typescript { .api }
7
function configure(config: Partial<Config> | ((existing: Config) => Partial<Config>)): void;
8
function getConfig(): Config;
9
10
interface Config {
11
/**
12
* Enable React.StrictMode wrapper by default for all renders
13
* Default: false
14
*/
15
reactStrictMode: boolean;
16
17
/**
18
* Attribute used for getByTestId and related queries
19
* Default: 'data-testid'
20
*/
21
testIdAttribute: string;
22
23
/**
24
* Default timeout for async utilities (waitFor, findBy, etc.) in milliseconds
25
* Default: 1000
26
*/
27
asyncUtilTimeout: number;
28
29
/**
30
* Custom function to compute accessibility names
31
*/
32
computedStyleSupportsPseudoElements?: boolean;
33
34
/**
35
* Default hidden value for queries
36
* Default: false
37
*/
38
defaultHidden?: boolean;
39
40
/**
41
* Show original stack trace on errors
42
* Default: false
43
*/
44
showOriginalStackTrace?: boolean;
45
46
/**
47
* Throw errors on multiple elements found (for singular queries)
48
* Default: true
49
*/
50
throwSuggestions?: boolean;
51
52
/**
53
* Custom getElementError function for better error messages
54
*/
55
getElementError?: (message: string | null, container: HTMLElement) => Error;
56
57
/**
58
* Wrapper for advancing timers in async operations
59
*/
60
unstable_advanceTimersWrapper?: (callback: () => void) => void;
61
62
/**
63
* Wrapper for async operations
64
*/
65
asyncWrapper?: (callback: () => Promise<any>) => Promise<any>;
66
67
/**
68
* Wrapper for event handlers
69
*/
70
eventWrapper?: (callback: () => void) => void;
71
}
72
```
73
74
## Common Setup
75
76
### Test Setup File
77
```typescript
78
// test-setup.js
79
import { configure } from '@testing-library/react';
80
import '@testing-library/jest-dom';
81
82
configure({
83
reactStrictMode: true,
84
asyncUtilTimeout: 2000,
85
testIdAttribute: 'data-testid',
86
});
87
```
88
89
Add to package.json or test config:
90
```json
91
{
92
"jest": {
93
"setupFilesAfterEnv": ["<rootDir>/test-setup.js"]
94
}
95
}
96
```
97
98
## Configuration Options
99
100
### reactStrictMode
101
102
Enable React.StrictMode wrapper by default for all renders. Helps identify potential problems in components.
103
104
```typescript
105
configure({ reactStrictMode: true });
106
107
// Now all renders will be wrapped in StrictMode
108
render(<App />);
109
110
// Equivalent to:
111
render(<App />, { reactStrictMode: true });
112
```
113
114
Can override per-render:
115
```typescript
116
render(<App />, { reactStrictMode: false });
117
```
118
119
### testIdAttribute
120
121
Change the attribute used by `getByTestId` and related queries. Useful when using a different testing convention.
122
123
```typescript
124
// Use custom attribute
125
configure({ testIdAttribute: 'data-test' });
126
127
// Now this works:
128
render(<div data-test="custom-element">Content</div>);
129
const element = screen.getByTestId('custom-element');
130
```
131
132
### asyncUtilTimeout
133
134
Set the default timeout in milliseconds for async utilities like `waitFor` and `findBy*` queries.
135
136
```typescript
137
// Increase timeout for slower operations
138
configure({ asyncUtilTimeout: 3000 });
139
140
// Now all async operations use 3 second timeout by default
141
await screen.findByText('Async content'); // Waits up to 3s
142
143
// Can still override per-call
144
await waitFor(() => {
145
expect(screen.getByText('Content')).toBeInTheDocument();
146
}, { timeout: 5000 }); // Override to 5s
147
```
148
149
### showOriginalStackTrace
150
151
Show original stack traces in errors instead of React Testing Library's cleaned-up versions.
152
153
```typescript
154
configure({ showOriginalStackTrace: true });
155
```
156
157
### throwSuggestions
158
159
Enable or disable helpful suggestions in error messages when queries fail.
160
161
```typescript
162
configure({ throwSuggestions: false });
163
```
164
165
### getElementError
166
167
Customize error messages when queries fail.
168
169
```typescript
170
import { configure } from '@testing-library/react';
171
172
configure({
173
getElementError: (message, container) => {
174
return new Error(`Custom error: ${message}\nContainer: ${container.innerHTML}`);
175
},
176
});
177
```
178
179
## Common Patterns
180
181
### Environment-Specific Config
182
```typescript
183
if (process.env.CI) {
184
configure({ asyncUtilTimeout: 5000 }); // Longer in CI
185
} else {
186
configure({ asyncUtilTimeout: 1000 }); // Faster locally
187
}
188
```
189
190
### Per-Test Config
191
```typescript
192
describe('slow tests', () => {
193
let originalConfig;
194
195
beforeEach(() => {
196
originalConfig = getConfig();
197
configure({ asyncUtilTimeout: 5000 });
198
});
199
200
afterEach(() => {
201
configure(originalConfig);
202
});
203
204
test('slow operation', async () => {
205
// Uses 5s timeout
206
});
207
});
208
```
209
210
### Function Form
211
Modify based on current config:
212
213
```typescript
214
configure((current) => ({
215
asyncUtilTimeout: current.asyncUtilTimeout * 2,
216
}));
217
```
218
219
## Global vs Per-Render
220
221
Some options can be set globally or per-render:
222
223
```typescript
224
// Global
225
configure({ reactStrictMode: true });
226
227
// Per-render (overrides global)
228
render(<App />, { reactStrictMode: false });
229
```
230
231
## Custom Error Messages
232
233
```typescript
234
configure({
235
getElementError: (message, container) => {
236
return new Error(`Custom: ${message}\n${container.innerHTML}`);
237
},
238
});
239
```
240
241
## Advanced Configuration
242
243
### Custom Async Wrapper
244
245
Control how async operations are wrapped:
246
247
```typescript
248
import { configure, act } from '@testing-library/react';
249
250
configure({
251
asyncWrapper: async (callback) => {
252
// Custom async handling
253
console.log('Before async operation');
254
const result = await callback();
255
console.log('After async operation');
256
return result;
257
},
258
});
259
```
260
261
### Custom Event Wrapper
262
263
Control how events are wrapped:
264
265
```typescript
266
import { configure, act } from '@testing-library/react';
267
268
configure({
269
eventWrapper: (callback) => {
270
// Custom event handling
271
act(() => {
272
console.log('Firing event');
273
callback();
274
});
275
},
276
});
277
```
278
279
### Timer Advancement Wrapper
280
281
Control timer advancement in async operations:
282
283
```typescript
284
import { configure, act } from '@testing-library/react';
285
286
configure({
287
unstable_advanceTimersWrapper: (callback) => {
288
act(() => {
289
callback();
290
});
291
},
292
});
293
```
294
295
## Important Notes
296
297
### Global vs Per-Render Configuration
298
299
Some options can be set globally via `configure()` or per-render via options:
300
301
```typescript
302
// Global
303
configure({ reactStrictMode: true });
304
305
// Per-render (overrides global)
306
render(<App />, { reactStrictMode: false });
307
```
308
309
### Configuration Persistence
310
311
Configuration changes persist across tests. Always restore original configuration if changing it temporarily:
312
313
```typescript
314
const originalConfig = getConfig();
315
316
// Modify config
317
configure({ asyncUtilTimeout: 5000 });
318
319
// ... tests ...
320
321
// Restore
322
configure(originalConfig);
323
```
324
325
### Partial Configuration
326
327
When using `configure()`, only specified options are updated. Other options remain unchanged:
328
329
```typescript
330
configure({ reactStrictMode: true }); // Only changes reactStrictMode
331
configure({ asyncUtilTimeout: 2000 }); // Only changes timeout, reactStrictMode stays true
332
```
333
334
### Function Form
335
336
Use the function form to modify configuration based on current values:
337
338
```typescript
339
configure((current) => ({
340
asyncUtilTimeout: current.asyncUtilTimeout * 2,
341
}));
342
```
343
344
## Relationship with @testing-library/dom Configuration
345
346
React Testing Library's `configure()` function extends @testing-library/dom's configuration. All dom configuration options are available:
347
348
- `testIdAttribute`
349
- `asyncUtilTimeout`
350
- `showOriginalStackTrace`
351
- `throwSuggestions`
352
- `getElementError`
353
- And others from @testing-library/dom
354
355
React Testing Library adds:
356
357
- `reactStrictMode` (React-specific)
358
- React-specific wrappers for `asyncWrapper`, `eventWrapper`, and `unstable_advanceTimersWrapper`
359
360
## Best Practices
361
362
1. **Set in test setup** - Configure once in setup file
363
2. **Restore after changes** - Save/restore when temporarily changing
364
3. **Use per-render overrides** - For exceptions, override at render time
365
4. **Match environment** - Adjust timeouts for CI vs local
366
5. **Enable StrictMode** - Catch issues early in development
367
368
## Default Values
369
370
```typescript
371
const defaultConfig = {
372
reactStrictMode: false,
373
testIdAttribute: 'data-testid',
374
asyncUtilTimeout: 1000,
375
showOriginalStackTrace: false,
376
throwSuggestions: true,
377
defaultHidden: false,
378
computedStyleSupportsPseudoElements: false,
379
};
380
```
381