utils.tsx
Overview
The utils.tsx file provides a collection of utility functions primarily designed to facilitate testing in React applications that use the SWR data fetching library. The utilities focus on asynchronous control (e.g., delaying execution, batching updates), rendering components with SWR configurations, simulating DOM events, generating unique keys, and mocking browser behaviors such as visibility state and console errors.
This file is intended to streamline writing robust and clean tests by abstracting common testing patterns, especially when working with asynchronous data fetching and React's concurrent rendering behavior.
Detailed Explanations
1. sleep(time: number): Promise<void>
Purpose: Returns a promise that resolves after a specified delay.
Parameters:
time(number): Time in milliseconds to wait before resolving.
Returns:
Promise<void>that resolves aftertimemilliseconds.Usage Example:
await sleep(1000); // waits for 1 secondDetails: Useful for simulating delays or waiting for asynchronous operations in tests.
2. createResponse<T>(response: T, { delay } = { delay: 10 }): Promise<T>
Purpose: Returns a promise that resolves or rejects with the provided response after a configurable delay.
Parameters:
response(T | Error): The value or error with which the promise will resolve or reject.Optional
{ delay }(object):delay(number, default10): Milliseconds to wait before resolving/rejecting.
Returns:
Promise<T>that resolves or rejects after the delay.Usage Example:
// Simulate successful fetch with 50ms delay await createResponse({ data: 'ok' }, { delay: 50 }); // Simulate error with default delay await createResponse(new Error('Network error'));Details: Helps simulate network latency or errors in tests.
3. nextTick(): Promise<void>
Purpose: Advances the React testing
act()cycle by one tick (about 1ms).Returns:
Promise<void>that resolves after a 1ms delay wrapped in React'sact().Usage Example:
await nextTick();Details: Used to flush pending React updates and effects in tests.
4. focusOn(element: any): Promise<void>
Purpose: Simulates focusing on a DOM element within a React testing
act()wrapper.Parameters:
element: The DOM element or React ref to focus.
Returns:
Promise<void>resolving after the focus event is fired.Usage Example:
await focusOn(inputElement);Details: Ensures React properly handles focus events during tests.
5. createKey(): string
Purpose: Generates a unique string key prefixed with
"swr-key-".Returns: A string like
"swr-key-1234567".Usage Example:
const key = createKey(); // "swr-key-9273648"Details: Useful for creating unique cache keys in SWR tests.
6. _renderWithConfig(element: React.ReactElement, config: SWRConfig['value']): ReturnType<typeof render>
Purpose: Internal helper to render a React element wrapped with an
SWRConfigprovider configured with the given options.Parameters:
element: React element to render.config: Configuration object for SWR (SWRConfig['value']).
Returns: Result of
@testing-library/react'srenderfunction.Usage: Private, used by other render helpers.
Details: Wraps rendered components with SWR context for isolated testing environments.
7. renderWithConfig(element: React.ReactElement, config?: SWRConfig['value']): ReturnType<typeof render>
Purpose: Renders a React element wrapped in an
SWRConfigprovider with a fresh cache provider (newMap()).Parameters:
element: React element to render.Optional
config: Additional SWR config options.
Returns: Render result from
@testing-library/react.Usage Example:
renderWithConfig(<MyComponent />, { refreshInterval: 0 });Details: Ensures each test has an isolated SWR cache.
8. renderWithGlobalCache(element: React.ReactElement, config?: SWRConfig['value']): ReturnType<typeof render>
Purpose: Renders a React element wrapped in an
SWRConfigprovider using the default global cache.Parameters:
element: React element to render.Optional
config: Additional SWR config options.
Returns: Render result from
@testing-library/react.Usage Example:
renderWithGlobalCache(<MyComponent />);Details: Shares cache globally, useful for testing cache persistence.
9. hydrateWithConfig(element: React.ReactElement, container: HTMLElement, config?: SWRConfig['value']): ReturnType<typeof render>
Purpose: Renders a React element into an existing DOM container with hydration enabled, wrapped in an
SWRConfigprovider with a fresh cache.Parameters:
element: React element to render.container: The HTML element to hydrate into.Optional
config: Additional SWR config options.
Returns: Render result from
@testing-library/react.Usage Example:
const container = document.createElement('div'); hydrateWithConfig(<App />, container);Details: Supports React hydration testing with legacy mode toggle via environment variable
TEST_REACT_LEGACY.
10. mockVisibilityHidden(): () => void
Purpose: Mocks the
document.visibilityStateproperty to always return'hidden'during tests.Returns: A function to restore the original visibility state.
Usage Example:
const restore = mockVisibilityHidden(); // ...test code here restore(); // restore original behaviorDetails: Useful for testing behavior dependent on page visibility.
11. executeWithoutBatching(fn: () => any): Promise<void>
Purpose: Executes a function with React's batching behavior disabled. This is relevant for React 18 where
act()batches updates by default.Parameters:
fn: Async or sync function to execute without batching.
Returns: Promise resolving after
fncompletes.Usage Example:
await executeWithoutBatching(() => { // code that should not be batched });Details: Temporarily disables React's
IS_REACT_ACT_ENVIRONMENTflag to avoid batching.
12. mockConsoleForHydrationErrors(): () => void
Purpose: Mocks
console.errorto suppress hydration warnings during tests and asserts that no hydration errors occurred.Returns: A function to restore console and perform the assertion.
Usage Example:
const restore = mockConsoleForHydrationErrors(); // ...run hydration test restore(); // checks no hydration warnings were logged and restores console.errorDetails: Helps catch unintended hydration mismatches and suppress noisy error logs during tests.
Important Implementation Details
The utilities leverage React Testing Library's
renderandactto simulate user interactions and React lifecycle behavior properly.They use the SWR context provider (
SWRConfig) to mock or isolate caches, allowing predictable data fetching behavior.executeWithoutBatchingmanipulates a global flag to control React 18's automatic batching during tests.Mocking functions utilize Jest spies to override native browser or console behaviors temporarily.
Interaction with Other Parts of the System
React Components: These utilities are designed to support testing React components, especially those using SWR for data fetching.
SWR Library: Central to this file is the use of SWR's
SWRConfigfor cache management and configuration during tests.React Testing Library: The file depends heavily on this library for rendering components and firing DOM events.
Jest: Mocking behaviors assume Jest as the test runner and mocking framework.
React 18 Features: Some utilities account for changes introduced in React 18, such as update batching and hydration.
Visual Diagram: Flowchart of Utility Functions and Their Relationships
flowchart TD
A[sleep(time)] -->|used by| B[nextTick()]
B -->|wraps| act
C[createResponse(response, delay)] -->|returns delayed Promise| D[Promise<T>]
E[focusOn(element)] -->|wraps| act
E -->|fires event| F[fireEvent.focus]
G[createKey()] -->|returns| H[String key]
I[_renderWithConfig(element, config)] -->|wraps| J[SWRConfig Provider]
I -->|calls| K[render()]
L[renderWithConfig(element, config?)] -->|calls| I with new Map() as provider
M[renderWithGlobalCache(element, config?)] -->|calls| I with default provider
N[hydrateWithConfig(element, container, config?)] -->|render with hydrate:true| O[render()]
N -->|wraps| J
P[mockVisibilityHidden()] -->|mocks| Q[document.visibilityState]
P -->|returns| R[restore function]
S[executeWithoutBatching(fn)] -->|disables| T[IS_REACT_ACT_ENVIRONMENT]
S -->|executes| fn
S -->|restores| T
U[mockConsoleForHydrationErrors()] -->|mocks| V[console.error]
U -->|returns| W[restore function with assertion]
Summary
utils.tsx is a specialized utility module to aid testing React components that use SWR. It provides asynchronous helpers, rendering wrappers with SWR contexts, event simulation, and environment mocking. These utilities help maintain test isolation, simulate real-world scenarios (like network delays and visibility changes), and handle React 18’s updated testing behaviors. The file plays a critical role in ensuring reliable and maintainable tests across the codebase.