use-swr-legacy-react.test.tsx


Overview

This file contains test cases specifically targeting the useSWR React hook and related mutation hooks within legacy React environments (React versions 17 and below). The primary focus is to verify that internal flags and behaviors related to legacy React compatibility, such as IS_REACT_LEGACY mode and React’s startTransition API, are correctly enabled and functional when using the swr library.

The tests ensure that useSWR and useSWRMutation hooks behave as expected under legacy React constraints, including proper handling of asynchronous mutations, state updates, and component unmount scenarios. This helps maintain backward compatibility and robustness of the SWR library across different React versions.


Detailed Explanation

Imports and Setup

Utility Function: withLegacyReact

async function withLegacyReact(runner: () => Promise<void>) {
  await jest.isolateModulesAsync(async () => {
    await runner()
  })
}
await withLegacyReact(async () => {
  // test logic here
});

Test Suites and Test Cases

describe('useSWR - legacy React', () => { ... })

Group of tests focused on verifying SWR behavior with legacy React.


Test Case 1: should enable the IS_REACT_LEGACY flag - startTransition

;(process.env.__SWR_TEST_BUILD ? it.skip : it)(
  'should enable the IS_REACT_LEGACY flag - startTransition',
  async () => {
    await withLegacyReact(async () => {
      // Test mutation and trigger
      const useSWRMutation = (await import('swr/mutation')).default

      const waitForNextTick = () =>
        act(() => new Promise(resolve => setTimeout(resolve, 1)))
      const key = Math.random().toString()

      function Page() {
        const { data, trigger } = useSWRMutation(key, () => 'data')
        return <button onClick={() => trigger()}>{data || 'pending'}</button>
      }

      render(<Page />)

      // mount
      await screen.findByText('pending')

      fireEvent.click(screen.getByText('pending'))
      await waitForNextTick()

      screen.getByText('data')
    })
  }
)

Test Case 2: should enable the IS_REACT_LEGACY flag - unmount check

;(process.env.__SWR_TEST_BUILD ? it.skip : it)(
  'should enable the IS_REACT_LEGACY flag - unmount check',
  async () => {
    await withLegacyReact(async () => {
      const useSWR = (await import('swr')).default

      const key = Math.random().toString()

      function Page() {
        // No fallback data
        const { data } = useSWR(
          key,
          () =>
            new Promise<string>(resolve =>
              setTimeout(() => resolve('data'), 100)
            ),
          {
            loadingTimeout: 10
          }
        )
        return <p>{data || 'pending'}</p>
      }

      render(<Page />)

      await screen.findByText('data')
    })
  }
)

Important Implementation Details


Interaction with Other Parts of the System


Usage Example Summary

This file itself is a test suite, but it provides examples on how to:


Mermaid Diagram - Component Interaction Flowchart

This flowchart illustrates the interaction flow within the test cases, showing the key functions and components involved in the legacy React testing scenario.

flowchart TD
    A[withLegacyReact] --> B[Dynamic import of SWR hooks]
    B --> C[Page Component]
    C --> D[useSWRMutation or useSWR Hook]
    C --> E[Render Button or Paragraph]
    E --> F[User Interaction (click)]
    F --> G[trigger() or SWR fetcher]
    G --> H[State update]
    H --> I[UI text changes: "pending" → "data"]
    I --> J[Assertions with screen queries]

    style A fill:#f9f,stroke:#333,stroke-width:2px
    style B fill:#bbf,stroke:#333,stroke-width:2px
    style C fill:#afa,stroke:#333,stroke-width:2px
    style D fill:#ffb,stroke:#333,stroke-width:2px
    style E fill:#ffd,stroke:#333,stroke-width:2px
    style F fill:#fbb,stroke:#333,stroke-width:2px
    style G fill:#bfb,stroke:#333,stroke-width:2px
    style H fill:#ddf,stroke:#333,stroke-width:2px
    style I fill:#fbf,stroke:#333,stroke-width:2px
    style J fill:#dfd,stroke:#333,stroke-width:2px

Summary


If you need more details on the SWR library itself or integration with React 18+ features, please refer to the core SWR documentation and React concurrent mode guides.