use-swr-integration.test.tsx
Overview
This file contains a comprehensive suite of integration tests for the SWR React hook, which is a data fetching library focused on caching, revalidation, and performance optimization in React applications. The tests verify the behavior and features of the useSWR hook under various scenarios, including:
Data fetching lifecycle (loading, success, error)
Cache sharing and deduplication
Handling of synchronous and asynchronous fetchers
Behavior with different SWR options like
revalidateOnMount,fallbackData, anddedupingIntervalBroadcasting of data, errors, and validation states across multiple components sharing the same key
Support for complex keys (arrays, objects, functions)
Nested hooks and revalidation logic
Edge cases related to rendering performance and data synchronization
This test file ensures the stability and correctness of SWR’s core integration within React components, simulating real-world usage patterns and edge cases.
Detailed Explanations
Test Suite: describe('useSWR', () => { ... })
This suite groups all the integration tests validating the useSWR hook behavior.
Important Imports
React and Testing Library utilities
act,screen,fireEventfrom@testing-library/react: used for simulating user interactions and asserting rendered output.
useSWR: The hook under test.Helpers from
./utils:createResponse: Simulates fetcher response (possibly with delay).sleep: Async delay helper.nextTick (aliased as
waitForNextTick): Waits for the next event loop tick.renderWithConfig,renderWithGlobalCache: Custom render helpers with specific SWR configurations or global cache.createKey: Generates unique keys for SWR cache.
Key Test Cases and Their Details
1. Hydration and Data Loading
it('should return `undefined` on hydration then return data', async () => { ... })
Purpose: Ensure that
useSWRreturnsundefinedinitially (hydration phase) and then returns resolved data.Usage: Simple component using
useSWR(key, fetcher).Assertions:
Initial render shows loading state (
hello,with no data).After data fetching, renders
hello, SWR.
2. Function as Key
it('should allow functions as key and reuse the cache', async () => { ... })
Purpose: Verify that
useSWRaccepts a function returning the key and caches accordingly.Implementation: Key is a function returning a shared key.
Result: Data is correctly fetched and displayed.
3. Async Fetcher Support
it('should allow async fetcher functions', async () => { ... })
Checks:
useSWRsupports asynchronous fetchers returning promises.Fetcher: Mocked with jest.fn returning a delayed response.
Outcome:
fetchercalled once; data displayed after promise resolves.
4. revalidateOnMount Behavior
When
revalidateOnMountis false, fetcher is not called on mount.When the key changes, fetcher is called even if
revalidateOnMountis false.When true and
fallbackDatais set, fetcher is always called on mount.
This is tested in multiple test cases to ensure reactive behavior based on config.
5. Loading and Validation States with fallbackData
it('initial loading state should be false when revalidation is disabled with fallbackData', async () => { ... })
Checks that
isLoadingandisValidatingflags are correctly set to false on initial render when no revalidation is triggered due to config options.
6. Request Deduplication
it('should dedupe requests by default', async () => { ... })
Verifies that multiple
useSWRcalls with the same key share the same fetcher call (only one request).Important for performance and avoiding redundant network calls.
7. onSuccess Callback
it('should trigger the onSuccess event', async () => { ... })
Validates that the
onSuccessoption callback is invoked with fetched data.
8. Broadcasting Updates Across Components
Data Broadcast: Multiple components with the same key receive synchronized updates.
Error Broadcast: Errors thrown in fetchers are broadcast to all components sharing the key.
Validation Broadcast:
isValidatingstate changes are broadcast.
This verifies SWR’s global cache and subscription model.
9. Complex Key Support (Arrays, Objects, Function returning args)
it('should accept object args', async () => { ... })
it('should accept function returning args', async () => { ... })
Tests that keys can be arrays or objects; SWR correctly serializes and caches based on these.
Also tests dynamic keys returned from functions.
10. Initial Data and Fallback Behavior
fallbackDatais used as initial data without triggering fetch unless configured.Revalidation still occurs when key changes, even with
fallbackData.
11. Config as Second Parameter
it('should set config as second parameter', async () => { ... })
Demonstrates alternate configuration style where fetcher is passed inside config instead of as second arg.
12. Revalidation and Deduping Interval
Test toggling component visibility and ensuring data is revalidated after deduping interval expiration.
13. Nested SWR Hooks
Nested hooks using the same key trigger loading state only once, improving render performance.
14. Rendering Performance and Retry Logic
Tests how many times components render during error and retry cycles.
Ensures minimal re-renders in best and worst cases.
15. Synchronous Data Access After Getter
it('should return latest data synchronously after accessing getter', async () => { ... })
Ensures that after data is fetched, subsequent synchronous reads of the data return the latest value.
Important Implementation Details
Use of
renderWithConfigandrenderWithGlobalCache: These helpers wrap components with SWR providers configured to simulate different caching and revalidation behaviors.Use of Jest mock functions to track fetcher call counts.
Use of React Testing Library: The tests rely on querying rendered DOM nodes to verify UI output after fetches.
Asynchronous testing with
await screen.findByText: Waits for UI to reflect updated SWR state.Use of React Profiler to count renders and ensure correct re-render behavior.
Deduplication and Broadcasting are core SWR features tested by multiple components reading/writing the same cache keys.
Interaction with Other Parts of the System
./utils: Provides utilities like key generation, response simulation, and enhanced render functions.SWR Library: This file tests the core hook implementation of SWR, which underpins data fetching in the application.
React Components: The tests simulate React components embedding the
useSWRhook, validating lifecycle and reactivity.Testing Framework: Jest and React Testing Library provide the testing environment.
Usage Examples Extracted from Tests
// Basic usage with a key and synchronous fetcher
function Page() {
const { data } = useSWR('my-key', () => 'Hello SWR')
return <div>{data}</div>
}
// Using function as key
function Page() {
const { data } = useSWR(() => 'my-key', () => 'Hello SWR')
return <div>{data}</div>
}
// Using async fetcher
function Page() {
const fetcher = async () => {
await sleep(100)
return 'Hello SWR'
}
const { data } = useSWR('my-key', fetcher)
return <div>{data}</div>
}
// Using fallbackData and disabling revalidation on mount
function Page() {
const { data, isLoading } = useSWR('my-key', fetcher, {
fallbackData: 'Initial Data',
revalidateOnMount: false
})
return <div>{isLoading ? 'Loading...' : data}</div>
}
Visual Diagram
The file is primarily a test suite containing multiple test functions but no classes. It tests the interaction between React components and the useSWR hook, focusing on how components share state through SWR's cache and revalidation mechanisms.
Hence, a component interaction diagram is most appropriate to illustrate the workflow of SWR usage and testing.
componentDiagram
component "React Component" as RC
component "useSWR Hook" as SWR
component "SWR Cache & Deduplication Layer" as Cache
component "Fetcher Function" as Fetcher
component "React Testing Library" as RTL
component "Test Utils" as Utils
RC --> SWR: calls useSWR(key, fetcher, config)
SWR --> Cache: reads/writes cached data
SWR --> Fetcher: calls fetcher to get data
Cache --> SWR: returns cached data or triggers fetch
RTL --> RC: renders component, simulates events
Utils --> RTL: provides render helpers
RTL --> SWR: triggers updates via component rerenders
Diagram explanation:
React components invoke
useSWRwith keys and fetchers.useSWRinteracts with the SWR cache layer to read/write data and manage deduplication.If data is stale or missing,
useSWRcalls the fetcher function.React Testing Library renders components and simulates user interactions to test component behavior.
Utility functions assist with rendering and timing control during tests.
Summary
This test file, use-swr-integration.test.tsx, is a critical part of the SWR library's test suite that verifies the stability, correctness, and performance optimizations of the useSWR hook in React applications. It covers a wide range of scenarios, including caching, revalidation, error handling, broadcasting data to multiple components, and integration with React lifecycle and hooks. The tests use mocked fetchers, custom render utilities, and React Testing Library to simulate realistic component behavior and interactions.
This documentation should help developers understand the purpose, coverage, and usage patterns of the tests within this file, as well as provide guidance for adding future tests or debugging SWR integration issues.