use-swr-devtools.test.tsx
Overview
This file is a test suite for verifying the integration and functionality of the SWR DevTools middleware within a React application using the useSWR hook from the SWR library. It ensures that:
Custom middleware defined on the global
window.SWR_DEVTOOLS_USEis properly applied touseSWR.The React instance used internally by SWR DevTools is the same as the one imported in the test, ensuring consistency of React references.
The tests leverage React Testing Library for rendering and querying DOM elements, and employ a custom test utility module (./utils) for creating keys, responses, and rendering with configuration.
File Structure and Detailed Explanations
1. Imports
screenfrom@testing-library/react: Provides utilities to query DOM elements rendered by React components.Reactfromreact: The React library instance, used for React reference checks.Dynamic imports inside
beforeEach:useSWRfromswr: The main data fetching hook under test.Utilities (
createKey,createResponse,renderWithConfig) from a local./utilsmodule to assist testing.
2. Test Suite: describe('useSWR - devtools', () => { ... })
The suite groups tests related to the SWR DevTools integration.
Variables declared outside tests:
useSWR: The SWR hook to be tested.createKey: Utility to generate keys for SWR cache.createResponse: Utility to create mock responses.renderWithConfig: Utility to render React components with necessary configuration.
3.1 beforeEach Hook
Runs before each test to:
Define a middleware function that decorates the
useSWRhook by overriding thedataproperty in the result with the string'middleware'.const middleware = useSWRNext => (...args) => { const result = useSWRNext(...args) return { ...result, data: 'middleware' } }Set
window.SWR_DEVTOOLS_USEglobal variable to an array containing this middleware, simulating how devtools inject middleware into SWR.Import the test utilities and
useSWRdynamically to ensure fresh imports for each test.
3.2 Test Case 1: 'window.__SWR_DEVTOOLS_USE__ should be set as middleware'
Creates a unique SWR key using
createKey().Defines a React component
Pagethat:Calls
useSWRwith the key and a fetcher returning a mock response (createResponse('ok')).Renders the
datafield inside a<div>.
Renders the component with
renderWithConfig.Asserts that the DOM contains text
'data: middleware', confirming that the middleware replaced the original data with'middleware'.
Usage example:
const key = createKey()
function Page() {
const { data } = useSWR(key, () => createResponse('ok'))
return <div>data: {data}</div>
}
renderWithConfig(<Page />)
// Expect: The text 'data: middleware' appears, showing middleware is applied.
3.3 Test Case 2: 'window.__SWR_DEVTOOLS_REACT__ should be the same reference with React'
Verifies that
window.SWR_DEVTOOLS_REACTglobal variable points to the same React instance imported in the test file.This is important to avoid React context mismatches or multiple React versions causing bugs.
Important Implementation Details
Middleware injection via global variable: The file simulates SWR DevTools behavior by setting a global middleware array
window.SWR_DEVTOOLS_USE. This approach allows SWR to pick up devtools middleware dynamically.Middleware function wraps
useSWR: The middleware wraps and intercepts theuseSWRhook call to override the returned data with a fixed value'middleware'.Dynamic import in
beforeEach: Ensures that each test uses a fresh instance ofuseSWRand utilities, isolating tests and their side effects.Use of
@ts-expect-error: Suppresses TypeScript errors for assigning non-standard properties on thewindowobject.
Interaction with Other Parts of the System
SWR library (
swrpackage): The core hook under test,useSWR, is from the official SWR data fetching library.SWR DevTools: This test file simulates part of the devtools integration by injecting middleware into the SWR hook.
./utilsmodule: Provides helper functions for generating keys, mock responses, and rendering components with configuration. This module likely encapsulates common test setup logic for SWR-related tests.React Testing Library: Used to render components and assert DOM content, facilitating testing of React components using SWR.
Visual Diagram: Component and Function Interaction Flow
flowchart TD
A[Global window object]
A -->|Sets| B[window.__SWR_DEVTOOLS_USE__ (middleware array)]
B --> C[Middleware function wraps useSWR]
D[useSWR hook]
C --> D
D -->|Returns| E[Result { data: 'middleware' }]
F[Page component]
F -->|Calls| D
F -->|Renders| G[<div>data: middleware</div>]
H[renderWithConfig]
H -->|Renders| F
I[React Testing Library screen]
I -->|findByText('data: middleware')| G
J[window.__SWR_DEVTOOLS_REACT__]
K[React import]
J ---|Reference equality check| K
Summary
This test file ensures that the SWR DevTools middleware correctly wraps the useSWR hook by overriding the data returned, and verifies that the React instance used by the devtools is consistent with the React instance imported in the application. It uses a middleware injection pattern via the global window object and employs React Testing Library for rendering and assertions.
The file is critical for maintaining the reliability of the devtools integration, ensuring that developers using SWR with devtools experience consistent and expected behavior during development and debugging.