use-swr-node-env.test.tsx
Overview
This file contains Jest-based unit tests focusing on verifying the behavior of the useSWR and useSWRImmutable React hooks from the SWR library when executed in a Node.js environment (i.e., server-side rendering). The tests specifically ensure that:
The environment detection constant
IS_SERVERcorrectly identifies the Node.js environment.useSWRproperly renders fallback data during server-side rendering.useSWRImmutabledoes not trigger revalidation on the server side.
The file uses React's renderToString method from react-dom/server to simulate server-side rendering of React components that use the SWR hooks.
Detailed Explanation
Imports
renderToString(fromreact-dom/server): Converts React components to HTML strings, simulating server-side rendering.useSWR(fromswr): React hook for data fetching with caching and revalidation capabilities.useSWRImmutable(fromswr/immutable): Variant ofuseSWRthat disables automatic revalidation.IS_SERVER(fromswr/_internal): Internal constant indicating if the code is running on the server.createKey(from local./utils): Utility function to generate unique keys for SWR caching.
Test Suite: useSWR
This test suite contains three test cases validating server-side behavior of SWR hooks.
1. Test: env IS_SERVER is true in node env
Purpose: Verify that the environment detection constant
IS_SERVERistruewhen running in Node.js (server environment).Implementation: Simple assertion checking the value of
IS_SERVER.Usage Example:
expect(IS_SERVER).toBe(true);
2. Test: should render fallback if provided on server side
Purpose: Ensure that when a fallback value (
fallbackData) is provided touseSWR, the data returned during server-side rendering matches the fallback.Implementation Details:
Generates a unique key via
createKey().Defines a custom hook
useDatathat callsuseSWRwith the key and a fetcher function returning the key itself.Provides a
fallbackDataoption with the string'fallback'.Defines a React component
Pagethat renders thedatainside a<p>tag.Renders the component to HTML string using
renderToString.Asserts that the rendered HTML contains the fallback string.
Usage Example:
const useData = () => useSWR(key, k => k, { fallbackData: 'fallback' }); function Page() { const { data } = useData(); return <p>{data}</p>; } const html = renderToString(<Page />); expect(html).toContain('fallback');
3. Test: should not revalidate useSWRImmutable on server side
Purpose: Verify that
useSWRImmutabledoes not attempt to revalidate data on the server (no fetch occurs).Implementation Details:
Generates a unique key via
createKey().Defines a custom hook
useDatausinguseSWRImmutablewith a fetcher function returning the key.React component
Pagerenders thedataor'empty'if no data exists.Renders the component to HTML string.
Asserts that the rendered HTML contains the string
'empty', indicating no data was fetched or revalidated.
Usage Example:
const useData = () => useSWRImmutable(key, k => k); function Page() { const { data } = useData(); return <p>{data || 'empty'}</p>; } const html = renderToString(<Page />); expect(html).toContain('empty');
Important Implementation Details
Environment Setup: The top comment
@jest-environment nodeinstructs Jest to run these tests in a Node environment, which is critical as the behavior being tested depends on server-side execution.Disabling ESLint Rule: The comment disables linting on render result naming conventions because the tests destructure the render result in an unconventional way.
Key Generation with
createKey: To avoid cache collisions and ensure test isolation, keys for SWR hooks are dynamically generated.Server-side Rendering Simulation: Using
renderToStringallows testing React components as they would render on the server, ensuring fallback data and revalidation behaviors are correct in SSR contexts.Immutable SWR Behavior:
useSWRImmutableis designed to never revalidate or mutate data once fetched, which is why the test ensures no data is present on the server (empty state).
Interaction with Other Parts of the System
SWR Library: This file tests internal SWR constants and hooks (
IS_SERVER,useSWR,useSWRImmutable), confirming their expected behavior in server environments../utilsModule: ImportscreateKeyutility for generating unique keys to use with SWR hooks.React Server Rendering: Utilizes React's server rendering API (
renderToString) to test how hooks behave during SSR.Testing Framework: Uses Jest to define and run tests, including assertions on rendered HTML.
These tests help maintain guarantees that server-side rendering with SWR works as expected, which is critical for applications that rely on SSR for performance or SEO.
Mermaid Diagram
The file is a test utility script primarily containing test functions with no classes or complex hierarchies. A flowchart illustrating the relationship between main functions and their flow during testing will be most helpful.
flowchart TD
A[Test Suite: useSWR] --> B[Test: IS_SERVER is true]
A --> C[Test: renders fallback on server]
A --> D[Test: useSWRImmutable no revalidation on server]
C --> E[createKey()]
C --> F[useSWR with fallbackData]
C --> G[Page component renders data]
C --> H[renderToString(Page)]
C --> I[Assert HTML contains 'fallback']
D --> J[createKey()]
D --> K[useSWRImmutable without revalidation]
D --> L[Page component renders data or 'empty']
D --> M[renderToString(Page)]
D --> N[Assert HTML contains 'empty']
Summary
This test file validates key aspects of the SWR React hooks in a Node.js environment, ensuring that:
The environment flag
IS_SERVERis accurate.useSWRcorrectly uses fallback data during SSR.useSWRImmutableavoids revalidation on the server side.
The tests use React server rendering and dynamically generated keys to simulate real-world SSR behavior and prevent interference between tests. This ensures robustness and correctness of data fetching hooks in server-rendered React applications.