use-swr-reconnect.test.tsx
Overview
This file contains a suite of unit tests for the useSWR React hook, specifically focusing on the behavior of data revalidation triggered by network reconnect events. The tests verify that the useSWR hook correctly re-fetches data when the browser regains network connectivity (online event), and respects configuration options that control this behavior.
The primary goal of these tests is to ensure that useSWR's automatic reconnection revalidation feature works as intended under various scenarios, such as default behavior, disabling revalidation via options, custom online state logic, and when the document is not visible.
Detailed Explanation
Test Suite: useSWR - reconnect
This test suite groups tests related to the reconnection behavior of the useSWR hook.
Test Case 1: should revalidate on reconnect by default
Purpose:
Verify thatuseSWRautomatically revalidates data upon network reconnection by default.Implementation Details:
A stateful value (
value) increments every time the fetcher function is called.A component
PageusesuseSWRwith a custom key and a fetcher that returns the incrementedvalue.The
dedupingIntervalis set to0to disable request deduplication and ensure every fetch triggers.The test simulates going offline and then online by firing corresponding events on the
window.The test asserts that the displayed data updates from
0to1after reconnection, indicating revalidation.
Usage Example:
function Page() { const { data } = useSWR('key', () => value++, { dedupingInterval: 0 }) return <div>data: {data}</div> }
Test Case 2: shouldn't revalidate on reconnect when revalidateOnReconnect is false
Purpose:
Ensure that if therevalidateOnReconnectoption is set tofalse,useSWRdoes not refetch data after reconnecting.Implementation Details:
Similar setup as Test Case 1.
The
useSWRhook receives the option{ revalidateOnReconnect: false }.After simulating offline and online events, the test asserts that the data remains unchanged (no revalidation).
Usage Example:
useSWR('key', fetcher, { dedupingInterval: 0, revalidateOnReconnect: false })
Test Case 3: shouldn't revalidate on reconnect when isOnline is returning false
Purpose:
Validate that if theisOnlineoption returnsfalse, indicating the app is offline regardless of browser events,useSWRdoes not revalidate on reconnect.Implementation Details:
The
isOnlineoption is overridden to always returnfalse.After simulating offline and online events, the data should remain the same.
This test confirms that
useSWRhonors the custom online state logic instead of just relying on browser events.
Usage Example:
useSWR('key', fetcher, { dedupingInterval: 0, isOnline: () => false })
Test Case 4: shouldn't revalidate on reconnect if invisible
Purpose:
Test that if the document is not visible (e.g., tab is hidden),useSWRdoes not revalidate on reconnect.Implementation Details:
The test uses a utility
mockVisibilityHidden()to simulate the document visibility state as hidden.The
isOnlineoption is set to returnfalse, preventing revalidation triggered by online status alone.After triggering offline and online events, the data remains unchanged.
The mock visibility is reset after the test to avoid side effects.
Usage Example:
const resetVisibility = mockVisibilityHidden() // ... run tests resetVisibility()
Important Implementation Details
Fetcher Function:
Each test uses a fetcher function that increments a local variable (value) to simulate changing data. This approach provides a simple way to verify if the hook refetched data.dedupingInterval: 0:
Set to disable request deduplication so that every fetch call results in a data update.Event Simulation:
Network status changes are simulated by firingofflineandonlineevents on thewindowobject usingfireEventandcreateEventfrom@testing-library/react.Visibility Mocking:
ThemockVisibilityHiddenutility temporarily simulates the document being hidden to test behavior when the page is not visible.Asynchronous Assertions:
The tests useawait screen.findByText(...)to wait for the DOM to update after asynchronous revalidation.
Integration with Other Parts of the System
useSWRHook:
The core hook under test, which is a widely-used React hook for data fetching with caching, revalidation, focus tracking, and more.Testing Utilities (
./utils):
This file imports various utilities such asrenderWithConfig,createKey,mockVisibilityHidden, andnextTickfrom a localutilsmodule to facilitate rendering, generating unique keys, simulating visibility, and waiting for asynchronous updates.Testing Library:
Utilizes@testing-library/reactfor rendering components and simulating user and system events.
This test file helps ensure that the network reconnect behavior of useSWR aligns with expected defaults and configurable options, improving reliability in offline/online scenarios.
Visual Diagram
Below is a component interaction flowchart illustrating the relationships between key functions and events in the tests:
flowchart TD
A[Start Test] --> B[Render <Page />]
B --> C[useSWR Hook]
C --> D[Fetcher function increments value]
B --> E[Display "data: {data}"]
F[Trigger offline event] --> G[fireEvent(window, offline)]
G --> H[Trigger online event] --> I[fireEvent(window, online)]
I --> J{Should revalidate?}
J -- Yes --> K[Fetcher called, value increments]
J -- No --> L[Data remains unchanged]
K --> E
L --> E
Summary
This file tests the useSWR hook's behavior concerning automatic data revalidation on network reconnect events, ensuring it properly respects configuration options like revalidateOnReconnect and isOnline, as well as document visibility state. It uses simulated network events and stateful fetchers to verify that the hook behaves as expected under different conditions, contributing to robust offline/online handling in applications using useSWR.