Simple and complete React DOM testing utilities that encourage good testing practices
—
Configure React Testing Library behavior globally or per-test.
function configure(config: Partial<Config> | ((existing: Config) => Partial<Config>)): void;
function getConfig(): Config;
interface Config {
/**
* Enable React.StrictMode wrapper by default for all renders
* Default: false
*/
reactStrictMode: boolean;
/**
* Attribute used for getByTestId and related queries
* Default: 'data-testid'
*/
testIdAttribute: string;
/**
* Default timeout for async utilities (waitFor, findBy, etc.) in milliseconds
* Default: 1000
*/
asyncUtilTimeout: number;
/**
* Custom function to compute accessibility names
*/
computedStyleSupportsPseudoElements?: boolean;
/**
* Default hidden value for queries
* Default: false
*/
defaultHidden?: boolean;
/**
* Show original stack trace on errors
* Default: false
*/
showOriginalStackTrace?: boolean;
/**
* Throw errors on multiple elements found (for singular queries)
* Default: true
*/
throwSuggestions?: boolean;
/**
* Custom getElementError function for better error messages
*/
getElementError?: (message: string | null, container: HTMLElement) => Error;
/**
* Wrapper for advancing timers in async operations
*/
unstable_advanceTimersWrapper?: (callback: () => void) => void;
/**
* Wrapper for async operations
*/
asyncWrapper?: (callback: () => Promise<any>) => Promise<any>;
/**
* Wrapper for event handlers
*/
eventWrapper?: (callback: () => void) => void;
}// test-setup.js
import { configure } from '@testing-library/react';
import '@testing-library/jest-dom';
configure({
reactStrictMode: true,
asyncUtilTimeout: 2000,
testIdAttribute: 'data-testid',
});Add to package.json or test config:
{
"jest": {
"setupFilesAfterEnv": ["<rootDir>/test-setup.js"]
}
}Enable React.StrictMode wrapper by default for all renders. Helps identify potential problems in components.
configure({ reactStrictMode: true });
// Now all renders will be wrapped in StrictMode
render(<App />);
// Equivalent to:
render(<App />, { reactStrictMode: true });Can override per-render:
render(<App />, { reactStrictMode: false });Change the attribute used by getByTestId and related queries. Useful when using a different testing convention.
// Use custom attribute
configure({ testIdAttribute: 'data-test' });
// Now this works:
render(<div data-test="custom-element">Content</div>);
const element = screen.getByTestId('custom-element');Set the default timeout in milliseconds for async utilities like waitFor and findBy* queries.
// Increase timeout for slower operations
configure({ asyncUtilTimeout: 3000 });
// Now all async operations use 3 second timeout by default
await screen.findByText('Async content'); // Waits up to 3s
// Can still override per-call
await waitFor(() => {
expect(screen.getByText('Content')).toBeInTheDocument();
}, { timeout: 5000 }); // Override to 5sShow original stack traces in errors instead of React Testing Library's cleaned-up versions.
configure({ showOriginalStackTrace: true });Enable or disable helpful suggestions in error messages when queries fail.
configure({ throwSuggestions: false });Customize error messages when queries fail.
import { configure } from '@testing-library/react';
configure({
getElementError: (message, container) => {
return new Error(`Custom error: ${message}\nContainer: ${container.innerHTML}`);
},
});if (process.env.CI) {
configure({ asyncUtilTimeout: 5000 }); // Longer in CI
} else {
configure({ asyncUtilTimeout: 1000 }); // Faster locally
}describe('slow tests', () => {
let originalConfig;
beforeEach(() => {
originalConfig = getConfig();
configure({ asyncUtilTimeout: 5000 });
});
afterEach(() => {
configure(originalConfig);
});
test('slow operation', async () => {
// Uses 5s timeout
});
});Modify based on current config:
configure((current) => ({
asyncUtilTimeout: current.asyncUtilTimeout * 2,
}));Some options can be set globally or per-render:
// Global
configure({ reactStrictMode: true });
// Per-render (overrides global)
render(<App />, { reactStrictMode: false });configure({
getElementError: (message, container) => {
return new Error(`Custom: ${message}\n${container.innerHTML}`);
},
});Control how async operations are wrapped:
import { configure, act } from '@testing-library/react';
configure({
asyncWrapper: async (callback) => {
// Custom async handling
console.log('Before async operation');
const result = await callback();
console.log('After async operation');
return result;
},
});Control how events are wrapped:
import { configure, act } from '@testing-library/react';
configure({
eventWrapper: (callback) => {
// Custom event handling
act(() => {
console.log('Firing event');
callback();
});
},
});Control timer advancement in async operations:
import { configure, act } from '@testing-library/react';
configure({
unstable_advanceTimersWrapper: (callback) => {
act(() => {
callback();
});
},
});Some options can be set globally via configure() or per-render via options:
// Global
configure({ reactStrictMode: true });
// Per-render (overrides global)
render(<App />, { reactStrictMode: false });Configuration changes persist across tests. Always restore original configuration if changing it temporarily:
const originalConfig = getConfig();
// Modify config
configure({ asyncUtilTimeout: 5000 });
// ... tests ...
// Restore
configure(originalConfig);When using configure(), only specified options are updated. Other options remain unchanged:
configure({ reactStrictMode: true }); // Only changes reactStrictMode
configure({ asyncUtilTimeout: 2000 }); // Only changes timeout, reactStrictMode stays trueUse the function form to modify configuration based on current values:
configure((current) => ({
asyncUtilTimeout: current.asyncUtilTimeout * 2,
}));React Testing Library's configure() function extends @testing-library/dom's configuration. All dom configuration options are available:
testIdAttributeasyncUtilTimeoutshowOriginalStackTracethrowSuggestionsgetElementErrorReact Testing Library adds:
reactStrictMode (React-specific)asyncWrapper, eventWrapper, and unstable_advanceTimersWrapperconst defaultConfig = {
reactStrictMode: false,
testIdAttribute: 'data-testid',
asyncUtilTimeout: 1000,
showOriginalStackTrace: false,
throwSuggestions: true,
defaultHidden: false,
computedStyleSupportsPseudoElements: false,
};Install with Tessl CLI
npx tessl i tessl/npm-testing-library--react@16.3.2