use-swr-preload.test.tsx
Overview
This file contains a comprehensive test suite for validating the behavior of the preload function from the useSWR data fetching library. The preload function is designed to prime the SWR cache with data before components mount, improving perceived performance and user experience by avoiding redundant or waterfall data fetching.
The tests cover scenarios such as:
Preloading data before the component mounts
Avoiding duplicate preload calls for the same resource
Preloading within React lifecycle methods (useEffect)
Integration with React Suspense mode
Preventing waterfall loading in multiple concurrent requests
Resetting cache on preload errors
Deduplication of requests during preload
Correct serialization of keys passed to the fetcher
The file uses React Testing Library and Jest to simulate component rendering, user interactions, and assert correct fetcher invocations and UI updates.
Detailed Explanation of Key Components
Test Suite: describe('useSWR - preload', () => { ... })
The test suite groups multiple test cases that validate the preload function's behavior when used alongside useSWR.
Test Cases
1. it('preload the fetcher function', async () => { ... })
Purpose: Validates that calling
preloadinvokes the fetcher once and the SWR hook uses the preloaded data without refetching.Key Steps:
Create a unique key and mock fetcher.
Call
preload(key, fetcher)and assert fetcher called once.Render a component using
useSWR(key, fetcher).Assert that data is displayed and fetcher is not called again.
Usage: Demonstrates basic preload usage to prime cache before component mount.
2. it('should avoid preloading the resource multiple times', async () => { ... })
Purpose: Ensures multiple calls to
preloadwith the same key do not cause multiple fetches.Key Steps:
Call
preload(key, fetcher)multiple times.Assert fetcher called only once.
Render component and ensure fetcher is still only called once.
Significance: Confirms deduplication of preload requests.
3. it('should be able to prealod resources in effects', async () => { ... })
Purpose: Tests that
preloadcan be called inside React effects (useEffect).Key Steps:
Call
preloadinside useEffect of a parent component.Render a child component using
useSWRwith the same key.Simulate user interaction to show child component.
Assert fetcher called once and data is loaded.
Usage: Useful when preloading depends on client-side lifecycle events.
4. it('preload the fetcher function with the suspense mode', async () => { ... })
Purpose: Validates preload behavior with React Suspense enabled in
useSWR.Key Steps:
Use
useSWR(key, fetcher, { suspense: true }).Wrap component with and React Profiler.
Assert fetcher called once and Profiler renders once.
Significance: Ensures preload works seamlessly with Suspense to avoid unnecessary fallbacks.
5. it('avoid suspense waterfall by prefetching the resources', async () => { ... })
Purpose: Prevent waterfall loading when multiple Suspense-enabled
useSWRhooks are used.Key Steps:
Preload multiple keys before rendering.
Render component with multiple SWR hooks, all with Suspense.
Assert that loading fallback appears only briefly.
Use sleep to simulate waiting time and confirm both data appear simultaneously.
Algorithmic Detail: Preloading both requests prevents sequential waits (waterfall), enabling parallel resolution.
6. it('reset the preload result when the preload function gets an error', async () => { ... })
Purpose: Tests cache reset behavior if
preloadresults in an error.Key Steps:
Preload a fetcher that initially throws an error, then returns data on retry.
Render component and verify error is displayed.
Trigger revalidation via SWR mutate.
Assert error is replaced by actual data.
Significance: Ensures preload errors don't poison the cache indefinitely.
7. it('dedupe requests during preloading', async () => { ... })
Purpose: Verifies deduplication of in-flight requests during preload along with re-renders.
Key Steps:
Preload a fetcher that resolves with delay.
Render component with deduping interval zero.
Rerender component while preload is in-flight.
Assert fetcher is called only once.
Confirm multiple Profiler render callbacks due to re-renders.
Usage: Important for preventing redundant fetches during rapid UI updates.
8. it('should pass serialize key to fetcher', async () => { ... })
Purpose: Ensures
preloadcorrectly serializes function keys before passing to fetcher.Key Steps:
Pass a function returning a key to
preload.Assert fetcher receives the serialized key string.
Significance: Validates key normalization for fetcher compatibility.
Important Implementation Details
Test Utilities Used:
createKey(): Generates unique keys for SWR cache.createResponse(data, options): Mocks fetcher responses with optional delay or error.renderWithGlobalCache(component): Renders components within a global SWR cache context.sleep(ms): Async delay helper to simulate network latency.
Testing Tools:
React Testing Library for rendering and interaction.
Jest for mocking and assertions.
React's
Profilercomponent to track render passes.Suspenseto test concurrent React features.
Core Algorithmic Concepts:
Deduplication: Ensures multiple preload calls for the same key only trigger one fetcher call.
Cache Priming: Preload populates SWR's cache to avoid fetching on component mount.
Suspense Integration: Preload supports React Suspense by resolving data before mount.
Error Handling: Preload errors reset cache to allow revalidation.
Waterfall Avoidance: Preloading multiple keys prevents sequential suspense fallbacks.
Interaction with Other Parts of the System
This test file depends on the SWR hooks (
useSWR,preload,useSWRConfig) from theswrpackage.Uses utility helpers from a local ./utils file to generate keys, mock responses, and render components.
Interacts with the React rendering lifecycle, especially in Suspense and Profiler contexts.
Validates the integration of
preloadwith SWR's caching and request deduplication mechanisms.Ensures that the SWR global cache is correctly primed and reset across various component states and renders.
Usage Example Snippet
import useSWR, { preload } from 'swr'
// Preload data before component mount
preload('/api/data', fetcherFunction)
function MyComponent() {
const { data, error } = useSWR('/api/data', fetcherFunction)
if (error) return <div>Error loading data</div>
if (!data) return <div>Loading...</div>
return <div>Data: {data}</div>
}
Mermaid Diagram: Flowchart of Main Functions and Their Relationships
flowchart TD
A[preload(key, fetcher)] -->|Calls once per unique key| B[fetcher function]
B --> C[Returns Promise or Response]
A --> D[Cache primed with data]
D --> E[useSWR(key, fetcher) reads from cache]
E --> F[Component renders with data]
A -.->|Error on preload| G[Cache reset]
E -->|Supports Suspense mode| H[React Suspense fallback]
A --> I[Deduplication prevents multiple fetches]
F --> J[Profiler tracks renders]
E --> K[useSWRConfig().mutate triggers revalidation]
Summary
This test file rigorously verifies the preload function's integration with the SWR data fetching library. It ensures that preloading behaves correctly under various conditions including multiple calls, React lifecycle effects, Suspense mode, error scenarios, and deduplication. By priming the SWR cache ahead of component mounts, it enables smoother and more efficient data fetching workflows in React applications. The tests also verify that preload cooperates correctly with React's concurrent rendering features and SWR's caching mechanisms to avoid redundant network requests and waterfall loading.
This file is crucial for maintaining the robustness and performance optimizations offered by SWR's preload capability within the overall application ecosystem.