use-swr-context-config.test.tsx
Overview
This file contains unit tests for validating the behavior of the SWR (stale-while-revalidate) React hooks and context configuration. It primarily focuses on:
Testing how
mutatebehaves when invoked before a component mounts.Verifying that the
useSWRConfighook returns a stable configuration object reference across multiple re-renders.
The tests leverage the React Testing Library and SWR's API (useSWR, mutate, SWRConfig, useSWRConfig) to validate the internal caching and configuration mechanisms in a React environment.
Detailed Explanation of Contents
Imports
React Testing Library:
act,render, screen for rendering components and simulating user interactions.SWR Library:
useSWR- hook to fetch and cache data.mutate- function to mutate cached data.SWRConfig- context provider for SWR configuration.useSWRConfig- hook to access current SWR configuration from context.
Local Utilities:
createKey,createResponse,renderWithGlobalCache- helper functions to generate keys, mock responses, and render components with a global cache preset.React Hooks:
useCallback,useEffect,useStatefor component state and memoization.
Test Suite 1: useSWR - context configs
Test: mutate before mount should not block rerender
Purpose:
To verify that calling
mutatebefore a component mounts (i.e., prefetching data into the cache) does not prevent the component from rendering and updating properly.
Implementation:
prefetchandfetcherare mock async functions returning different mock data strings.A unique
keyis generated for the cache.mutate(key, prefetch)is called before the component mounts to prefill the cache.The functional component
PageusesuseSWR(key, fetcher)to fetch data.renderWithGlobalCacherenders the component.Assertions check:
Initial render shows the prefetched data (
prefetch-data).Later update shows the fetched data (
data).
Key Points:
Confirms SWR handles prefilled caches gracefully.
Ensures no render-blocking occurs due to cache mutation.
Usage Example:
await mutate(key, prefetch); // prefill cache
function Page() {
const { data } = useSWR(key, fetcher);
return <div>{data}</div>;
}
renderWithGlobalCache(<Page />);
// Initially shows 'prefetch-data', then updates to 'data'.
Test Suite 2: useSWRConfig hook maintains stable reference across re-renders
Test: should maintain the same swrConfig reference when counter updates
Purpose:
To verify that the object returned by
useSWRConfig()remains referentially stable (same reference) across component state updates that do not affect the SWR context.
Implementation:
A
parentConfigobject is provided as the value toSWRConfigcontext.The
Pagecomponent wrapsChildComponentinSWRConfig.The
ChildComponent:Calls
useSWRConfig()to get SWR config.Holds a local counter state with a button to increment it.
Uses
useEffectto track how many times theswrConfigreference changes.
The test simulates clicking the counter button 3 times.
It asserts that the reference to
swrConfigonly changed once (on initial mount).
Key Points:
Ensures SWR context configuration object is memoized or stable.
Prevents unnecessary downstream re-renders in components consuming SWR config.
Usage Example:
const parentConfig = { revalidateOnMount: true, ... };
function Page() {
return (
<SWRConfig value={parentConfig}>
<ChildComponent />
</SWRConfig>
);
}
function ChildComponent() {
const swrConfig = useSWRConfig();
const [count, setCount] = useState(0);
useEffect(() => {
// Track swrConfig reference changes
}, [swrConfig]);
return <button onClick={() => setCount(c => c + 1)}>counter + 1</button>;
}
Important Implementation Details / Algorithms
Prefetching cache with
mutate: The test verifies that callingmutateasynchronously before mounting a component populates SWR's cache without blocking React's rendering lifecycle. This is critical for server-side rendering or hydrating initial data.Stable reference with
useSWRConfig: By checking the reference equality ofswrConfig, this test ensures that SWR's internal context provider returns a consistent configuration object. This avoids unnecessary re-renders and improves performance.
Interaction with Other Parts of the System
useSWRhook: The core hook under test; these tests verify how it behaves with context configuration and cache mutation.mutatefunction: Used to update SWR's global cache manually, simulating prefetch or cache priming.SWRConfig/useSWRConfig: Provide and consume global configuration for SWR hooks. These tests ensure the context behaves correctly and efficiently.Local utilities (
createKey,createResponse,renderWithGlobalCache): Assist in creating consistent test data and environment, simulating realistic SWR usage scenarios.React Testing Library: Provides rendering and interaction capabilities to simulate real user and lifecycle behavior in tests.
These tests primarily verify integration and behavior at the intersection of React components, SWR caching, and global configuration management.
Mermaid Diagram
This file is a test file focusing on functional test flows rather than classes or components with methods. Therefore, a flowchart illustrating the main test flows and their relationships is the most appropriate visualization.
flowchart TD
A[Start Test Suite: useSWR - context configs] --> B[mutate before mount test]
B --> B1[Call mutate(key, prefetch) before mount]
B1 --> B2[Render Page component using useSWR(key, fetcher)]
B2 --> B3[Assert: Prefetch data rendered]
B3 --> B4[Assert: Fetched data rendered]
A2[Start Test Suite: useSWRConfig hook stability] --> C[Render Page with SWRConfig]
C --> C1[ChildComponent uses useSWRConfig()]
C1 --> C2[Track swrConfig reference changes]
C2 --> C3[Simulate button clicks to increment counter]
C3 --> C4[Assert swrConfig reference changed only once]
style A fill:#f9f,stroke:#333,stroke-width:2px
style A2 fill:#f9f,stroke:#333,stroke-width:2px
Summary
The use-swr-context-config.test.tsx file validates critical behaviors of the SWR React library related to:
Prefetching data into the cache before component mount without blocking renders.
Ensuring that the global SWR configuration context returns a referentially stable object to prevent unnecessary re-renders.
These tests help maintain the correctness, performance, and usability of SWR in React applications that rely on context configs and manual cache mutations. The file leverages React Testing Library for realistic component lifecycle and interaction simulation.